import { _decorator, Component, find, instantiate, Node } from 'cc';
import { UIBase } from '../Components/UIBase';
import { CarColorsGlobalInstance } from '../CarColorsGlobalInstance';
import { UINames } from '../CarColorsGlobalTypes';
import { GlobalData, ConfigKeys } from '../../../ScriptFrame/GlobalData';
import { GlobalMgr } from 'db://assets/ScriptFrame/Frame/GlobalMgr';
import { AdvertMgr } from 'db://assets/ScriptFrame/Frame/AdvertMgr';
const { ccclass, property } = _decorator;

@ccclass('HomePage')
export class HomePage extends UIBase {
    @property(Node)
    startBtn: Node = null
    show(opts?: any): void {
        super.show(opts)
        this.startBtn.active = true

        GlobalMgr.instance.initilize()
        AdvertMgr.instance.initilize()
        AdvertMgr.instance.showInterstitial()
    }
    async startGame() {
        this.startBtn.active = false

        find("Scene/Parkings").children.forEach((child, index) => {
            if (index < 4) {
                child.name = "empty"
            } else {
                child.name = "lock"
                child.children[0].children[0].active = false
                child.children[0].children[1].active = true
            }
            child.children[1]?.destroy()
            child.children[1]?.removeFromParent()
        })
        find("Scene/Levels").destroyAllChildren()
        find("Scene/Levels").removeAllChildren()
        CarColorsGlobalInstance.instance.roleSysterm.clearAll()
        CarColorsGlobalInstance.instance.carSysterm.clearAll()
        CarColorsGlobalInstance.instance.bundleSysterm.loadLevels(GlobalData.instance.getConfigData(ConfigKeys.GameSaveData).level).then((level) => {
            console.log("instantiate(level)")
            const Level = instantiate(level)
            find("Scene/Levels").addChild(Level)
            for (let i = 0; i < Level.children.length; i++) {
                CarColorsGlobalInstance.instance.carSysterm.addCar(Level.children[i])
            }

            AdvertMgr.instance.showInterstitial()

            CarColorsGlobalInstance.instance.roleSysterm.initLevel()
            CarColorsGlobalInstance.instance.uiSysterm.showUI(UINames.GamePage)
            CarColorsGlobalInstance.instance.uiSysterm.hideUI(UINames.HomePage)


        }).catch((err) => {
            console.log(err)
            CarColorsGlobalInstance.instance.toastSysterm.showToast("关卡正在制作中")
            this.startBtn.active = true
            CarColorsGlobalInstance.instance.uiSysterm.hideUI(UINames.GamePage)
        })
    }
}

