import {maxBy, minBy} from "lodash";

type Cell = { row: number, col: number };

function parseCell(cell: string): Cell {
    const [row, col] = cell.split('_').map(Number);
    return {row, col};
}

function stringifyCell(cell: Cell): string {
    return `${cell.row}_${cell.col}`;
}

function intropolate(cells: Cell[]) {
    const interpolatedCells: Cell[] = [];
    for (let i = 0; i < cells.length - 1; i++) {
        const current = cells[i];
        const next = cells[i + 1];
        interpolatedCells.push(current);
        if (current.row === next.row) {
            for (let col = current.col + 1; col < next.col; col++) {
                interpolatedCells.push({row: current.row, col});
            }
        }
    }
    interpolatedCells.push(cells[cells.length - 1]);
    return interpolatedCells;
}

export function processSelectedCells(prevCells: string[], newSelection: string): string[] {
    const newCell = parseCell(newSelection);
    let cells = intropolate([...prevCells, newSelection].map(parseCell).sort((a, b) => a.col - b.col));
    const maxCell = maxBy(cells, cell => cell.col);
    const minCell = minBy(cells, cell => cell.col);
    const indexOfNewCell = cells.findIndex(cell => (cell.col === newCell.col && cell.row === newCell.row));

    if (minCell && maxCell) {
        if (newCell.col > minCell.col && newCell.col < maxCell.col) {
            if (indexOfNewCell >= (cells.length / 2))
                cells = cells.slice(0, indexOfNewCell);
            else
                cells = cells.slice(indexOfNewCell);
        }
    }

    return cells.map(stringifyCell);
}