import * as React from 'react';
import { FunctionComponent, useContext, useEffect, useMemo } from 'react';
import { DecorationsContext } from '../../contexts/DecorationsContext';
import { EditorViewContext } from '../../contexts/EditorViewContext';

import './LineDecorations.css';

type Props = {
  viewLineNumber: number;
  content: string;
};

export const LineDecorations: FunctionComponent<Props> = (props) => {
  const { viewLineNumber, content } = props;
  const { renderingContext: ctx } = useContext(EditorViewContext);
  const { decorations } = useContext(DecorationsContext);

  const children = useMemo(() => {
    if (!ctx) {
      return [];
    }

    for (const decoration of decorations) {
      if (decoration.options.isWholeLine) {
        continue;
      }

      const startPosition = decoration.range.getStartPosition();
      const endPosition = decoration.range.getEndPosition();

      const viewStartPosition = startPosition;
      const viewEndPosition = endPosition;

      if (viewStartPosition.lineNumber === viewLineNumber) {
        const first = content.slice(0, viewStartPosition.column - 1);
        if (viewLineNumber === viewEndPosition.lineNumber) {
          const second = content.slice(
            viewStartPosition.column - 1,
            viewEndPosition.column - 1
          );
          return [
            <span className={'first'}>{first}</span>,
            <span className={'second'}>{second}</span>,
          ];
        }
        const second = content.slice(viewStartPosition.column - 1);
        return [
          <span className={'first'}>{first}</span>,
          <span className={'second'}>{second}</span>,
        ];
      }

      if (
        viewStartPosition.lineNumber < viewLineNumber &&
        viewLineNumber < viewEndPosition.lineNumber
      ) {
        const first = '';
        const second = content;
        return [
          <span className={'first'}>{first}</span>,
          <span className={'second'}>{second}</span>,
        ];
      }
      if (viewEndPosition.lineNumber === viewLineNumber) {
        const first = ''; //content.slice(0, viewEndPosition.column - 1);
        const second = content.slice(0, viewEndPosition.column - 1);
        return [
          <span className={'first'}>{first}</span>,
          <span className={'second'}>{second}</span>,
        ];
      }
    }
    return [];
  }, [decorations, viewLineNumber, content, ctx]);

  return <div className={'line-decorations'}>{children}</div>;
};
