import { GlobalVariables } from "../Data/GlobalVariables";
import LocalStorage from "../Data/LocalStorage";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Levels extends cc.Component {
  @property(cc.SpriteFrame) lockSprite: cc.SpriteFrame = null;
  @property(cc.SpriteFrame) star1: cc.SpriteFrame = null;
  @property(cc.SpriteFrame) star2: cc.SpriteFrame = null;
  @property(cc.SpriteFrame) star3: cc.SpriteFrame = null;

  static instance: Levels = null;

  currentLevel: number = 0;
  onClickLevel: number = 0;
  highestUnlockedLevel: number;

  onLoad() {
    Levels.instance = this;
    this.addCustomEventData();
    this.highestUnlockedLevel = LocalStorage.getHighestLevel();
    this.updateLevelStatus();
  }

  addCustomEventData() {
    for (let i = 0; i < this.node.children.length; i++) {
      let button = this.node.children[i].getComponent(cc.Button);
      button.clickEvents[0].customEventData = i.toString();
    }
  }

  loadScene(event: Event, customEventData: string) {
    let lv = parseInt(customEventData);
    if (lv >= LocalStorage.getHighestLevel()) return;
    LocalStorage.setCurrentLevel(lv);
    GlobalVariables.levelToLoad = lv;
    cc.director.loadScene("gameplay");
  }

  updateLevelStatus() {
    let levelButtons = this.node.children;

    for (let i = 0; i < levelButtons.length; i++) {
      const e = levelButtons[i];
      const star = e.getChildByName("Star");
      if (i >= LocalStorage.getHighestLevel()) {
        star.active = false;
      }
      if (LocalStorage.getStarAtLevel(i + 1) == 1) {
        star.getComponent(cc.Sprite).spriteFrame = this.star1;
        star.scaleX = 0.3;
      } else if (LocalStorage.getStarAtLevel(i + 1) == 2) {
        star.getComponent(cc.Sprite).spriteFrame = this.star2;
        star.scaleX = 0.7;
      } else if (LocalStorage.getStarAtLevel(i + 1) == 3) {
        star.getComponent(cc.Sprite).spriteFrame = this.star3;
      } else star.active = false;

      if (i >= this.highestUnlockedLevel) {
        e.getComponent(cc.Sprite).spriteFrame = this.lockSprite;
        e.getComponentInChildren(cc.Label).node.active = false;
      }
    }
  }
}
