
import { LQCollide } from "../lq_collide_system/lq_collide";
import { EConfigConst } from "./game/cfg/ConfigDef";
import { ConfigMgr } from "./game/cfg/configMgr";
import { SmallLevelItem } from "./game/cfg/smallLevelItem";
import { Utils } from "./game/common/utils";
import levelempty from "./game/level/levelempty";
import { NestCondition } from "./game/level/nestCondition";
import { NestConditionMgr } from "./game/level/nestConditionMgr";
import { NestPlay } from "./game/nest/nestPlay";
import { ResMgr } from "./game/res/resMgr";
import { GameSysLogic } from "./game/update/gameSysLogic";

/**
 * 1 关卡有多个 飞机巢穴
 * 2 一个飞机巢穴属性：动画，位置，怪物 
 *  类型1  数量，时间间隔，延时
 */

let pass = 5;


enum LevelState {
    none,
    loading,
    playing,
}

/**
 * 1 切换关卡
 */
export class LevelMgr extends GameSysLogic {

    layer: cc.Node;
    title: cc.Label;
    passCnt: number = 0;
    state = LevelState.none;
    nestArr: NestPlay[] = [];
    conditionArr: NestCondition[] = [];

    private static _inst: LevelMgr;
    mgr: NestConditionMgr;
    public static get inst(): LevelMgr {
        if (this._inst == null) {
            this._inst = new LevelMgr();
            this._inst.init();
        }
        return this._inst;
    }

    init(){
    }

    gameUpdateSec(dt){
        if(this.state != LevelState.playing) return;
        if(this.layer.getComponentsInChildren(LQCollide).length > 0) return;

        if(!this.mgr.isDone()) return;

        for (let index = 0; index < this.nestArr.length; index++) {
            const element = this.nestArr[index];
            if(!element.isDone()) return;
        }

        this.next();
    }

    getMonsterCnt(){
        return this.layer.getComponentsInChildren(LQCollide).length;
    }
    
    async begin(){
        this.passCnt = 0;
        pass = ConfigMgr.inst.getCfgKeys(EConfigConst.smallLevel).length;

        this.load();
    }

    load(){
        this.title.string = `level${this.passCnt + 1}`;
        this.loadSmallLevel();
    }

    async loadSmallLevel(){
        this.layer.destroyAllChildren();
        this.nestArr = [];
        this.conditionArr = [];
        this.state = LevelState.loading;

        this.mgr && this.mgr.destroy();

        let node = await ResMgr.inst.loadPrefab(`level/levelEmpty`, this.layer);
        let levelView = node.getComponent(levelempty);
        let levelData = ConfigMgr.inst.getCfgClassById<SmallLevelItem>(EConfigConst.smallLevel, this.passCnt+1, SmallLevelItem);

        // this.nestCreate(levelData);

        let task = [];
        let obj = Utils.strToJson(levelData.data.nest1);
        obj.forEach(v=>{
            let nestNode = Utils.createNode(levelView.$top_node, `nest-[level:${this.passCnt+1}]nest1`);
            let nestPlay = nestNode.addComponent(NestPlay);
            let p = nestPlay.init(v[0],v[1]);
            task.push(p);

            this.nestArr.push(nestPlay);
        });

        await Promise.all(task);

        this.state = LevelState.playing;

        this.mgr = new NestConditionMgr();
        this.mgr.init(levelData);
        this.mgr.start();
        this.mgr.call=(cnt: number) =>{
            let nestKey = `nest${cnt+2}`;
            let obj = Utils.strToJson(levelData.data[nestKey]);
            obj.forEach(v=>{
                let nestNode = Utils.createNode(levelView.$top_node, `nest-[level:${this.passCnt+1}]${nestKey}`);
                let nestPlay = nestNode.addComponent(NestPlay);
                nestPlay.init(v[0],v[1]);
                this.nestArr.push(nestPlay);
            });
        }

        // for (let index = 2; index < 6; index++) {
        //     let nestKey = `nest${index}`;
        //     let intervalKey = `interval${index}`;
        //     if(levelData.data[nestKey] == '' || levelData.data[intervalKey] == '') break;
            
        //     let condition = new NestCondition();
        //     condition.fill(levelData.data[intervalKey]);
        //     condition.call = ()=>{
        //         let obj = Utils.strToJson(levelData.data[nestKey]);
        //         obj.forEach(v=>{
        //             let nestNode = Utils.createNode(levelView.$top_node, `nest-[level:${this.passCnt+1}]${nestKey}`);
        //             let nestPlay = nestNode.addComponent(NestPlay);
        //             nestPlay.init(v[0]);
        //             this.nestArr.push(nestPlay);
        //         });
        //     }
        //     condition.start();

        //     condition.name = `[level:${this.passCnt+1}]${intervalKey}`;

        //     this.conditionArr.push(condition);
        // }


        // let nestPos = levelData.getNestId();
        // let task = [];
        // nestPos.forEach(v=>{
        //     let nestNode = Utils.createNode(levelView.$top_node, 'nest');
        //     let p = this.fillNest(nestNode, v);
        //     task.push(p);
        // });

        // await Promise.all(task);
        // this.state = LevelState.playing;
    }


    skip(num: number){
        cc.log('skip-', num);
        if(num  > pass) return;
        if(num < 1) return;

        this.passCnt = num-1;
        this.load();
    }

    next(){
        if(this.passCnt + 1 >= pass) return;
        this.passCnt ++;
        this.load();
    }

    pre(){
        if(this.passCnt <= 0) return;
        this.passCnt--;
        this.load();
    }

    getMax(){
        return pass;
    }
    
    private loadPrefabLevel() {
        this.state = LevelState.loading
        this.title.string = `level${this.passCnt + 1}`;
        this.layer.destroyAllChildren();
        ResMgr.inst.loadPrefab(`level/level${this.passCnt + 1}`, this.layer).then(()=>{
            this.state = LevelState.playing;
        });
    }
}