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

const { ccclass, property } = cc._decorator;

@ccclass
export default class StartScene extends cc.Component {
  @property(cc.SpriteFrame) soundOffSprite: cc.SpriteFrame = null;
  @property(cc.SpriteFrame) soundOnSprite: cc.SpriteFrame = null;
  @property(cc.Node) animNode: cc.Node = null;

  sprite: cc.Sprite = null;
  currentSprite: cc.SpriteFrame;
  pressed: boolean = false;
  highestUnlockedLevel: number;
  currentAnimation: string = null;

  onLoad() {
    this.currentSprite = this.soundOnSprite;
    this.highestUnlockedLevel = LocalStorage.getHighestLevel();
    LocalStorage.getCurrentLevel();
    this.setPosAnimation();
    this.updateAllStarLabel();
    this.currentAnimation = "DogRun";
    this.animNode
      .getComponent(cc.Animation)
      .on("lastframe", this.onLastFrame, this);
    this.node
      .getChildByName("CoinLabel")
      .getComponent(cc.Label).string = `x${LocalStorage.getAllCoin()}`;
  }

  updateAllStarLabel() {
    let sum = 0;
    for (const item of LocalStorage.getAllStars()) {
      if (item.hasOwnProperty("star")) {
        sum += item.star;
      }
    }
    this.node
      .getChildByName("StarLabel")
      .getComponent(cc.Label).string = `${sum}/90`;
  }

  onLastFrame() {
    if (this.currentAnimation === "DogRun") {
      this.currentAnimation = "DogRolling";
    } else {
      this.currentAnimation = "DogRun";
    }

    this.animNode
      .getChildByName("Dog")
      .getComponent(cc.Animation)
      .play(this.currentAnimation);
  }

  setPosAnimation() {
    const startPos = -cc.winSize.width / 2 + this.animNode.x;
    const endPos = cc.winSize.width / 2 - this.animNode.x;
    const frameAnim = this.animNode.getComponent(cc.Animation).defaultClip
      .curveData.props;

    frameAnim.x[0].value = startPos;
    frameAnim.x[1].value = endPos + 150;
    frameAnim.x[2].value = endPos;
    frameAnim.x[3].value = startPos - 150;

    if (startPos <= 1000)
      this.animNode.getComponent(cc.Animation).defaultClip.speed = 0.4;
  }

  onClickButtonSound() {
    if (this.currentSprite === this.soundOnSprite) {
      this.currentSprite = this.soundOffSprite;
      cc.audioEngine.setMusicVolume(0);
      cc.audioEngine.setEffectsVolume(0);
    } else {
      this.currentSprite = this.soundOnSprite;
      cc.audioEngine.setMusicVolume(1);
      cc.audioEngine.setEffectsVolume(1);
    }
    this.updateButtonSprite();
  }

  updateButtonSprite() {
    const button = this.node
      .getChildByName("ButtonSound")
      .getComponent(cc.Button);
    const sprite = button.node.getComponent(cc.Sprite);
    sprite.spriteFrame = this.currentSprite;
  }

  onClickButtonPlay() {
    GlobalVariables.levelToLoad = this.highestUnlockedLevel - 1;
    cc.director.loadScene("gameplay");
  }
}
