import LocalStorage from "../Data/LocalStorage";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SkinController extends cc.Component {
  @property(cc.Node) coinLabel: cc.Node = null;
  @property(cc.Node) playerSkins: cc.Node = null;
  @property(cc.Node) enemySkins: cc.Node = null;

  allCoin: number;
  allSkins: Array<{ skin: string; available: boolean }>;

  protected onLoad(): void {
    this.allCoin = LocalStorage.getAllCoin();
    this.allSkins = LocalStorage.getAllSkins();
    this.updateStatus();
  }

  updateStatus() {
    this.coinLabel.getComponent(cc.Label).string = `x${this.allCoin}`;

    for (let i = 0; i < this.allSkins.length; i++) {
      let skin = this.allSkins[i];
      if (skin.available == true) {
        // Kiểm tra playerSkins
        for (let j = 0; j < this.playerSkins.children.length; j++) {
          let playerSkin = this.playerSkins.children[j];
          if (playerSkin.name === skin.skin) {
            let buttonBuy = playerSkin.getChildByName("ButtonBuy");
            if (buttonBuy) {
              buttonBuy.active = false;
            }
          }
        }

        // Kiểm tra enemySkins
        for (let k = 0; k < this.enemySkins.children.length; k++) {
          let enemySkin = this.enemySkins.children[k];
          if (enemySkin.name === skin.skin) {
            let buttonBuy = enemySkin.getChildByName("ButtonBuy");
            if (buttonBuy) {
              buttonBuy.active = false;
            }
          }
        }
      }
    }
  }

  onClickBuySkin(event: cc.Event.EventTouch) {
    if (this.allCoin >= 500) {
      event.currentTarget.active = false;
      LocalStorage.setAllCoin(this.allCoin - 500);
      this.allCoin = LocalStorage.getAllCoin();
      LocalStorage.setSkinAvailability(event.currentTarget.parent.name, true);
      this.coinLabel.getComponent(cc.Label).string = `x${this.allCoin}`;
    }
  }

  onClickChooseSkin(event: cc.Event.EventTouch) {
    let skin = event.currentTarget;
    if (skin.parent.getChildByName("ButtonBuy").active == true) return;
    skin.parent.getChildByName("SelectedZone").active = true;

    if (skin.parent.parent.name == "SkinPlayers") {
      for (let i = 0; i < this.playerSkins.children.length; i++) {
        let playerSkin = this.playerSkins.children[i];
        if (playerSkin.name != skin.parent.name) {
          let selectedZone = playerSkin.getChildByName("SelectedZone");
          if (selectedZone) {
            selectedZone.active = false;
          }
        }
      }
    }

    if (skin.parent.parent.name == "SkinEnemys") {
      for (let i = 0; i < this.enemySkins.children.length; i++) {
        let enemySkin = this.enemySkins.children[i];
        if (enemySkin.name != skin.parent.name) {
          let selectedZone = enemySkin.getChildByName("SelectedZone");
          if (selectedZone) {
            selectedZone.active = false;
          }
        }
      }
    }
  }
}
