import {
  INotebookModel,
  Notebook,
  NotebookActions
} from '@jupyterlab/notebook';

export const useNotebookInjection = () => {
  let replaceCellIndex = 0;

  const insertCode = (
    notebook: Notebook,
    model: INotebookModel,
    code: string,
    replaceCode: boolean
  ) => {
    const activeCellIndex = notebook.activeCellIndex;
    const cells = notebook.widgets;
    const searchString = '# Code generated by eodag-labextension,';
    const isReplaceCellExist =
      cells.filter(cell => cell.node.innerText.includes(searchString)).length >
      0;

    const getCodeCell = (code: string) => {
      return {
        cell_type: 'code',
        metadata: {
          trusted: false,
          collapsed: false,
          tags: ['Injected by EODAG plugin']
        },
        source: code
      };
    };

    if (cells.length > 0) {
      cells.forEach((cell, index) => {
        if (cell.node.innerText.includes(searchString)) {
          replaceCellIndex = index;
        }
      });
    }
    const cell = getCodeCell(code);

    if (replaceCode && isReplaceCellExist) {
      notebook.activeCellIndex = replaceCellIndex;
      NotebookActions.deleteCells(notebook);
      model.sharedModel.insertCell(replaceCellIndex, cell);
      notebook.activeCellIndex = replaceCellIndex;
    }

    if (replaceCode && !isReplaceCellExist) {
      replaceCellIndex = !cells[activeCellIndex].model.sharedModel.getSource()
        ? activeCellIndex
        : activeCellIndex + 1;

      if (activeCellIndex === replaceCellIndex) {
        NotebookActions.deleteCells(notebook);
      }

      model.sharedModel.insertCell(replaceCellIndex, cell);
      NotebookActions.selectBelow(notebook);
    }

    if (!replaceCode) {
      model.sharedModel.insertCell(activeCellIndex + 1, cell);
      NotebookActions.selectBelow(notebook);
    }
  };

  return {
    insertCode
  };
};
