import { isValid, Prefab, warn, Node, instantiate } from "cc";
import Utils from "../utils/Utils";
import WindowManager from "./WindowManager";

export enum BUSY_TYPE {
    NET,//网络
    RES//加载资源
}
export default class BusyLoadingManager {
    private static instance = null;
    private busyMap: Map<BUSY_TYPE, number> = new Map();
    private loadingUI: Node;
    private timerID: number = null
    private delay: number = 300//延迟显示
    constructor() {

    }
    public static get ins(): BusyLoadingManager {
        if (BusyLoadingManager.instance == null) {
            BusyLoadingManager.instance = new BusyLoadingManager();
        }
        return BusyLoadingManager.instance;
    }
    public async init() {
        let res = await Utils.loadRes('common/BusyLoading', "prefabs", Prefab)
        this.loadingUI = instantiate(res) as Node;
        this.loadingUI.name = "BusyLoading"
        // this.loadingUI.zIndex = 999
    }
    public addBusy(type: BUSY_TYPE) {
        let count = this.busyMap.get(type)
        if (count)
            this.busyMap.set(type, count + 1)
        else
            this.busyMap.set(type, 1)
        this.checkBusy()

    }
    public removeBusy(type: BUSY_TYPE) {
        let count = this.busyMap.get(type)
        if (count)
            this.busyMap.set(type, count - 1)
        else
            warn('remove busy error', type)
        this.checkBusy()
    }
    public async checkBusy() {
        if (this.loadingUI == null || !isValid(this.loadingUI)) {
            await this.init()
        }
        var count = this.getBusyCount()
        if (count > 0) {
            let self = this;
            let onTimerEnd = () => {
                let curCnt = this.getBusyCount()
                if (curCnt > 0) {
                    // self.loadingUI.opacity = 255;
                    self.updateTips();
                } else {
                    warn('timeout end waitcnt is 0')
                }
                this.timerID = null;
            }
            if (this.timerID) {
                clearTimeout(this.timerID);
                this.timerID = setTimeout(onTimerEnd, this.delay);
            } else {
                if (this.loadingUI.parent) {
                    this.updateTips();
                } else {
                    // this.loadingUI.opacity = 0;
                    WindowManager.ins.container.addChild(this.loadingUI)
                    this.timerID = setTimeout(onTimerEnd, this.delay);
                }
            }
        } else {
            if (this.timerID) {
                clearTimeout(this.timerID);
                this.timerID = 0;
            }
            if (this.loadingUI.parent) {
                this.loadingUI.removeFromParent();
            }
        }
    }
    private updateTips() {

    }
    private getBusyCount() {
        let c = 0;
        this.busyMap.forEach((v, k) => {
            c += v;
        })
        return c;
    }
}