import { InternalAnnotationTypeEnum } from '../../annotations/annotation.abstract';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
import { NodeAnnotationTypeEnum } from '../../annotations/node-annotation.abstract';
/**
 * Delete the corresponding link group
 */
export class DeleteLinkGroupStrategy extends ActionHandleStrategy {
  /**
   * Delete the corresponding link group
   *
   * @param {DeleteLinkGroupAction} _action - The delete link group action.
   * @param {RTETextNode} target - The text node that need to remove link annotation.
   */
  handleAction(_action, target) {
    const linkGroupAnnotation = target.parent.getAnnotationByType(InternalAnnotationTypeEnum.LINK_GROUP);
    if (linkGroupAnnotation) {
      const currentGroupKey = target.annotationMap.get(NodeAnnotationTypeEnum.LINK).link.groupKey;
      const currentLinkGroup = linkGroupAnnotation.linkGroups.get(currentGroupKey);
      if (currentLinkGroup) {
        const index = currentLinkGroup.indexOf(target);
        if (index !== -1) {
          currentLinkGroup.splice(index, 1);
        }
        if (currentLinkGroup.length === 0) {
          linkGroupAnnotation.linkGroups.delete(currentGroupKey);
        }
        if (linkGroupAnnotation.linkGroups.size === 0) {
          target.parent.annotationMap.delete(InternalAnnotationTypeEnum.LINK_GROUP);
        }
      }
    }
    target.annotationMap.delete(NodeAnnotationTypeEnum.LINK);
  }
}
