const BottleType = require('Types').BottleType;
const ModeType = require('Types').ModeType;
const Spawn = require('Spawn');
const Roll = require('Roll');

const WaveRandom = cc.Class({
    name: 'WaveRandom',
    properties: {
        spawns: {
            default: [],
            type: Spawn,
        },
        score: {
            default: 5000,
            type: cc.Integer
        }
    },
    ctor() {
        this.spawns = [];
    },
    /**
     * 瓶体类型
     * {0: 小瓶; 1: 中瓶; 2: 大瓶; 3: 特大瓶}
     */
    init(typeNum) {
        let spawns = [];
        /** 特大瓶一屏最多6个 */
        let limit = typeNum == 3 ? 6 : 7

        for(let i = 0; i < limit; i++) {
            let res = cc.random0To1()

            let sp = new Spawn()
            sp.init({
                bottleType: typeNum,
                total: 1
            })
            sp.isFake = res > 0.4 ? false : true;
            spawns.push(sp)
        }
        spawns[0].isFake = false;
        spawns[limit - 1].isFake = false;

        this.spawns = spawns
        this.totalBottles = 0;
        this.spawnIdx = 0;
        for (let i = 0; i < this.spawns.length; ++i) {
            this.totalBottles += this.spawns[i].total;
        }
    },
    getNextSpawn() {
        this.spawnIdx++;
        if (this.spawnIdx < this.spawns.length) {
            return this.spawns[this.spawnIdx];
        } else {
            return null;
        }
    }
})

cc.Class({
    extends: cc.Component,

    properties: {
        startWaveIdx: 0,
    },

    init(game) {
        this.game = game;
        // this.shooter = game.shooter;
        this.vSize = cc.director.getVisibleSize();
        this.bottleWrap = game.bottleWrap;
        this.waveIdx = this.startWaveIdx;
        this.spawnIdx = 0;
        this.bottleIdx = 0;
        this.bottleList = [];
        this.waveType = 3;      //{0: 小瓶; 1: 中瓶; 2: 大瓶; 3: 特大瓶}
        this.MoveX = 350;
        this.ModeType = 'normal';
        this.endTime = 0;
        /**
         * 0: 初始状态
         * 1: 量产中
         * 2: 等待中
         * 3: 结束量产
         */
        this.state = 0;
        this.endState = 0;

        this.waitTime = 0;

        this.resetSpecialMode();        

        this.currentWave = new WaveRandom();
    },

    /**
     * 开始量产
     */
    // startSpawn() {
    //     this.schedule(this.spawnBottle, 0);
    // },

    /**
     * 结束量产
     */
    // endSpawn() {
    //     // this.unschedule(this.spawnBottle);
    //     let nextSpawn = this.currentWave.getNextSpawn();
    //     if (nextSpawn) {
    //         this.currentSpawn = nextSpawn;
    //         this.startSpawn();
    //     } else {
    //         this.state = 2;
    //         this.waitTime = 0;
    //         // this.endWave();
    //         // console.log('end');
    //     }
    // },
    /**
     * 量产瓶子
     */
    spawnBottle() {
        // if (this.currentSpawn.finished) {
        //     this.endSpawn();
        //     return;
        // }
        let _spawns = this.currentWave.spawns;
        
        _spawns.forEach((n, index) => {
            this.scheduleOnce(() => {
                if(!n.isFake) {
                    let newBottle = n.spawn(this.game.bottleMng);
                    if (newBottle) {
                        this.bottleList[this.bottleIdx] = newBottle
                        this.bottleWrap.addChild(newBottle);
                        newBottle.setPosition(this.getNewBottlePosition(n));
                        newBottle.getComponent('Bottle').init(this);
                    }
                }
                this.bottleIdx++
            }, 0.1 * index)
        })

        /** 结束量产 */
        this.scheduleOnce(() => {
            this.state = 2;
            this.waitTime = 0;
        }, 0.2)
    },

    /**
     * 记录当前波段生成的特殊模式
     * @param {String} mode 特殊模式名称{subline: 辅助线瓶; bingo: 华彩瓶; hit: 必中瓶}
     */
    recordSpecialMode (mode) {
        this.modeRecord[mode] = true;
    },

    /**
     * 检查当前波段生成的特殊模式
     * @param {String} mode 特殊模式名称{subline: 辅助线瓶; bingo: 华彩瓶; hit: 必中瓶}
     */
    checkSpecialMode (mode) {
        return this.modeRecord[mode]
    },

    /**
     * 重置特殊模式
     */
    resetSpecialMode () {
        this.modeRecord = {
            subline: false,     //辅助线瓶
            bingo: false,       //华彩瓶
            hit: false,         //必中瓶
        };
    },

    startWave () {
        this.state = 1;
        this.bottleIdx = 0;
        // this.unschedule(this.spawnBottle);
        this.currentWave.init(this.waveType);
        this.currentSpawn = this.currentWave.spawns[this.currentWave.spawnIdx];
        this.spawnBottle();
        this.game.inGameUI.showWave();
    },

    restartWave () {
        this.waveIdx = this.startWaveIdx;
        this.spawnIdx = 0;
        this.bottleIdx = 0;
        this.bottleList = [];
        this.waveType = 2;
        this.endTime = 0;
        this.endState = 0;

        this.waitTime = 0;

        this.waveIdx++;
        this.currentWave = new WaveRandom(this.waveType);
        this.startWave();
    },

    /**
     * 结束生成
     */
    endWave () {
        this.endState = this.state;

        this.state = 3;
    },

    /**
     * 继续生成
     */
    continueWave () {
        this.state = this.endState;
    },

    /**
     * 重复生成
     */
    repeatWave() {
        console.log(`=========== repeatWave: ${this.waveIdx} ===========`);
        this.state = 0;
        this.waitTime = 0;

        //重置特殊模式
        this.resetSpecialMode();
        this.waveIdx++;
        this.currentWave = new WaveRandom(this.waveType);
        this.startWave();
    },

    /**
     * 改变类型
     */
    changeWave() {
        let score = this.game.inGameUI.score;
        //1~20分都为超大瓶体
        if (score <= 20) {
            this.waveType = 3;
        } else if (score > 20 && score <= 60) {
            let wtype = Math.floor(cc.random0To1() * 3) + 1;
            //华彩模式下不出现特大瓶
            if(this.game.gameMode == 'bingo' && wtype == 3) {
                wtype = 2;
            }
            this.waveType = wtype
        } else {
            let wtype = Math.floor(cc.random0To1() * 3);
            this.waveType = wtype
        }
    },

    /**
     * 改变速度
     */
    changeSpeed(speed) {
        this.MoveX = speed;
        // if(this.speedLevel == this.speedMap.length - 1) {
        //     this.speedLevel = 0;
        // } else {
        //     this.speedLevel += 1;
        // }
        // this.MoveX = this.speedMap[this.speedLevel];
    },

    /**
     * 销毁瓶子
     */
    despawnBottle(bottle) {
        let bottleType = bottle.bottleType;
        this.scheduleOnce(() => {
            this.game.bottleMng.returnBottle(bottleType, bottle.node);
        }, 0.2)
    },

    /**
     * 生成瓶子位置
     */
    getNewBottlePosition(n) {
        /** 根据瓶体类型不同的特殊偏移量（X轴） */
        let posT = n.bottleType == 3 ? 60 : 30;
        /** 瓶子宽度 */
        let sWidth = 124;
        /** 瓶子高度 */
        let sHeight = n.size.height;
        /** X轴整体偏移量 */
        let disX = cc.director.getVisibleSize().width / (this.vSize.width > 1550 ? 7 : 5);
        /** 瓶子容器高度(暂时写死) */
        let disY = 322;
        /** Y轴偏移量 */
        let posY = sHeight / 2 - 5;
        /** X轴偏移量 */
        let posX = (sWidth + posT) * (this.bottleIdx - 1) + disX;
        return cc.p(-posX, posY);
    },

    update(dt) {
        if(this.state == 3) {
            return
        }

        if(this.game.gameMode == 'hit') {
            this.endWave()
        } else if(this.state == 2) {
            this.waitTime += dt * 1000;
            /** 根据瓶体类型定义不同的重置波段间隔，特大瓶体为4.8秒后重置， */
            let waitLimit = this.waveType == 3 ? 4800 : 4000;
            if(this.waitTime >= waitLimit) {
                this.repeatWave();
            }
        }
    }
});