import { PID, UID } from "../persist";
import { AbstractCmdController } from "./abstractCmdController";

export interface FilterOption {
  filterMarkParagraph?: boolean;
  filterIncludeUids?: UID[]; // empty mean no people, undefined mean all people
  filterTags?: string[];
  filterUnfix?: boolean; // default true
}

export class ParagraphFilterController extends AbstractCmdController {
  private filterOption: FilterOption = {};

  setFilterOption(filterOption: FilterOption) {
    this.filterOption = filterOption;
  }

  getFilterOption() {
    return this.filterOption;
  }

  isPidVisible(pid: PID) {
    const paragraph = this.controller.getParagraph(pid);
    const words = this.controller.getWords(pid);

    const {
      filterMarkParagraph,
      filterIncludeUids,
      filterTags,
      filterUnfix = true,
    } = this.filterOption;

    if (filterUnfix === false && paragraph.isUnfix) {
      return true;
    }

    if (filterMarkParagraph && !this.controller.isHasParagraphMarkColor(pid)) {
      return false;
    }

    if (filterIncludeUids) {
      if (filterIncludeUids.length === 0) {
        return false;
      }
      if (!filterIncludeUids.includes(paragraph.uid!)) {
        return false;
      }
    }

    if (filterTags && filterTags.length > 0) {
      const { length } = filterTags;
      let isFound = false;
      for (let i = 0; i < length; i++) {
        const tag = filterTags[i];
        const found = words.find(word => word.tag === tag);
        if (found) {
          isFound = true;
          continue;
        }
      }
      if (!isFound) {
        return false;
      }
    }

    return true;
  }

  reset() {
    this.setFilterOption({});
  }
}
