import { isNonNullable } from '../../../../../types/type-guard';
import { BoldAnnotationAction } from '../../actions/bold-annotation-action';
import { ClearFormattingAnnotationAction } from '../../actions/clear-formatting-annotation-action';
import { CodeAnnotationAction } from '../../actions/code-annotation-action';
import { DeleteNodeAnnotationAction } from '../../actions/delete-node-annotation-action';
import { ItalicAnnotationAction } from '../../actions/italic-annotation-action';
import { LinkAnnotationAction } from '../../actions/link-annotation-action';
import { LinkGroupAnnotationAction } from '../../actions/link-group-annotation-action';
import { StrikethroughAnnotationAction } from '../../actions/strikethrough-annotation-action';
import { UnderlineAnnotationAction } from '../../actions/underline-annotation-action';
import { ClearFormattingAnnotation } from '../../annotations/clear-formatting-annotation';
import { NodeAnnotation } from '../../annotations/node-annotation.abstract';
import { SelectionRangeAnnotation } from '../../annotations/selection-range-annotation';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * The current strategy used to modify the text node annotation map.
 */
export class NodeUpdateAnnotationMapStrategy extends ActionHandleStrategy {
  /**
   * Remove or set annotation to the text node annotation map.
   *
   * @param {AnnotationAction} action - The annotation action instance.
   * @param {RTETextNode} target - The current text node.
   */
  handleAction(action, target) {
    const annotation = action.toAnnotation();
    if (action instanceof DeleteNodeAnnotationAction) {
      target.annotationMap.delete(action.annotationType);
      return;
    }
    if (annotation instanceof ClearFormattingAnnotation) {
      annotation.items.forEach((item) => {
        target.deleteAnnotationByType(item);
      });
      return;
    }
    if (annotation instanceof NodeAnnotation || annotation instanceof SelectionRangeAnnotation) {
      if (action instanceof LinkAnnotationAction) {
        if (isNonNullable(action.newText)) {
          target.text = action.newText;
        }
        target.parent.apply(new LinkGroupAnnotationAction(action.link.groupKey, [target], action.type));
      }
      if (action instanceof CodeAnnotationAction) {
        this.handleAction(new ClearFormattingAnnotationAction(), target);
      }
      if (action instanceof BoldAnnotationAction) {
        this.updateCustomStyleAnnotation(target, ['fontWeight']);
      }
      if (action instanceof ItalicAnnotationAction) {
        this.updateCustomStyleAnnotation(target, ['fontStyle']);
      }
      if (action instanceof UnderlineAnnotationAction ||
        action instanceof StrikethroughAnnotationAction) {
        this.updateCustomStyleAnnotation(target, ['textDecoration']);
      }
      target.annotationMap.set(annotation.type, annotation);
      return;
    }
  }
}
