import { _decorator, Component, Node } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { Hall } from "../hall/Hall";
import { EditBox } from "cc";
import { Tips } from "../../scripts/mgr/Tips";
const { ccclass, property } = _decorator;

export interface OnInputFinish {
  (name: string): void;
}

@ccclass("InputNameLayer")
export class InputNameLayer extends BaseUI {
  private onInputFinish: OnInputFinish = null!;
  private onCancel?: () => void;

  static async show(maxLength: number): Promise<string | null> {
    return new Promise(async (resolve) => {
      let page = await Hall.ins.showLayer("prefab/family/InputNameLayer");
      let comp = page.getComponent(InputNameLayer);
      comp.init(
        maxLength,
        (name) => {
          resolve(name);
        },
        () => {
          resolve(null);
        }
      );
    });
  }
  private _maxLength: number = 10;

  private _inputEditBox: EditBox;
  init(maxLength: number, onInputFinish: OnInputFinish, onCancel?: () => void) {
    this._maxLength = maxLength;
    this.onInputFinish = onInputFinish;
    this.onCancel = onCancel;

    this._inputEditBox = this.FindAs("input_edit_box", EditBox);
    this._inputEditBox.maxLength = maxLength;
    this._inputEditBox.string = "";

    this.setText("lbl_input_info", `Max ${maxLength} characters`);
    //on textchange
    // this._inputEditBox.node.on(Node.EventType.Chang, () => {
    //   this.setText("lbl_input_info", `${this._inputEditBox.string.length}/${maxLength}`);
    // });
  }

  protected simpleOnBtnClick(name: string): void {
    switch (name) {
      case "btn_close":
        this.onCancel?.();
        break;
      case "btn_confirm":
        let editBox = this.FindAs("input_edit_box", EditBox);
        editBox.string = editBox.string.trim();
        if (editBox.string.length == 0) {
          Tips.show("Please input something");
          return;
        }
        console.log("editBox", editBox.string);
        this.onInputFinish(editBox.string);
        this.closePage();
        break;
    }
  }
}
