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

export interface TextPolishResult {
  et: number; // 段落开始时间
  st: number; // 段落结束时间
  formal_paragraph: string; // 段落改写后的结果
  formal_validity: boolean; // 本段落是否改写成功(无效字段，移除判断)
  sentence_ids: number[]; // 被改写的句子id
}

export interface FixParagraphTextPolish {
  pid: PID; // 段落ID
  textPolishResult: TextPolishResult; // 段落文案信息
  isTextPolishing?: boolean; // 是否处在加载中
  isTextPolishError?: boolean; // 是否错误
}

export type FixParagraphTextPolishMap = Record<PID, FixParagraphTextPolish>;

/** AI原文改写的展示模式 */
export enum TextPolishMode {
  OriginAndTextPolish, // 展示原文和AI改写
  TextPolishOnly, // 仅展示AI改写
  Disabled, // 不展示AI改写
}

export class TextPolishController extends AbstractCmdController {
  private textPolishMode: TextPolishMode = TextPolishMode.Disabled; // 默认改写模式

  private fixParagraphTextPolish: FixParagraphTextPolishMap = {}; // 仅展示原文改写内容

  /**
   * 设置AI改写模式
   * @param newMode 新改写模式
   */
  setTextPolishMode(newMode: TextPolishMode) {
    this.textPolishMode = newMode;
    this.controller.emit("textPolishModeChange", { textPolishMode: newMode });
    if (newMode === TextPolishMode.Disabled) this.reset();
  }

  /** 获取当前AI改写模式 */
  getTextPolishMode() {
    return this.textPolishMode;
  }

  /** 通过单词来设置AI改写的内容 */
  setTextPolish(pid: PID, textPolish: TextPolishResult) {
    // 1.无段落信息，进行初始化
    if (!this.fixParagraphTextPolish[pid]) {
      this.fixParagraphTextPolish[pid] = {
        pid,
        textPolishResult: textPolish,
        isTextPolishError: false,
      };
    }
    // 4. 信息变更通知
    this.controller.emit("fixParagraphTextPolishChange", {
      pid,
      textPolish: this.fixParagraphTextPolish[pid],
    });
    return true;
  }

  /**
   * 根据段落Id获取AI改写段落信息
   * @param pid 段落id
   * @returns
   */
  getTextPolish(pid: PID) {
    return this.fixParagraphTextPolish[pid];
  }

  // 重置内容
  reset() {
    this.fixParagraphTextPolish = {};
  }
}
