// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { GAME_NAME } from "../Data/Constans";
import LocalStorage from "../Data/LocalStorage";
import LuckySpinScreen from "./Screen/LuckySpinScreen";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TimerSpin extends cc.Component {

    @property(cc.Label)
    timerLabel: cc.Label = null;

    @property(cc.Node)
    nodeLuckySpin: cc.Node = null;

    luckySpin: LuckySpinScreen = null;
    time: number = 12 * 60 * 60;

    public static Instance: TimerSpin = null;

    protected onLoad(): void {
        window.addEventListener('unload', this.unloadHandler.bind(this));
        TimerSpin.Instance = this;
        this.luckySpin = this.nodeLuckySpin.getComponent(LuckySpinScreen);
    }

    unloadHandler() {
        cc.sys.localStorage.setItem(GAME_NAME + "_REMAININGTIME", Math.floor(Date.now() / 1000).toString());
        cc.sys.localStorage.setItem(GAME_NAME + "_ELAPSESTIME", this.time);
    }

    protected start(): void {

        if (!LocalStorage.getIsFreeSpin()) {
            const storedTime = cc.sys.localStorage.getItem(GAME_NAME + "_REMAININGTIME");
            const timeCount = cc.sys.localStorage.getItem(GAME_NAME + "_ELAPSESTIME");
            const storedTimestamp = parseInt(storedTime);
            const currentTime = Math.floor(Date.now() / 1000);
            const elapsedTime = currentTime - storedTimestamp;
            this.time = timeCount;
            this.time -= elapsedTime;
            this.updateTimerLabel();
            this.startTimerSpin();
        }

    }

    startTimerSpin() {
        LocalStorage.setSpin(false);
        this.schedule(this.updateCountdown, 1);
    }

    updateCountdown() {
        this.time = this.time - 1;
        cc.sys.localStorage.setItem(GAME_NAME + "_REMAININGTIME", Math.floor(Date.now() / 1000).toString());
        cc.sys.localStorage.setItem(GAME_NAME + "_ELAPSESTIME", this.time);
        this.updateTimerLabel();
        if (this.time <= 0) {
            LocalStorage.setSpin(true);
            this.luckySpin.activeButtonSpin();
            this.unschedule(this.updateCountdown);
            this.time = 12*60*60;
        }
    }

    updateTimerLabel() {
        const hours = Math.floor(this.time / 3600);
        const minutes = Math.floor((this.time % 3600) / 60);
        const seconds = this.time % 60;

        const formattedTime = `${this.formatNumber(hours)}:${this.formatNumber(minutes)}:${this.formatNumber(seconds)}`;
        this.timerLabel.string = formattedTime;
    }

    formatNumber(value: number): string {
        return value < 10 ? `0${value}` : value.toString();
    }

}
