
import { _decorator, Component, Node, Prefab, Size, UITransform, Vec3, v3, size, rect } from 'cc';
import { GameMgr } from './GameMgr';
import { ObjPool } from './ObjPool';
const { ccclass, property } = _decorator;


let outPos = v3();

@ccclass('EnemySpawner')
export class EnemySpawner extends Component {
    @property({
        type: Prefab
    })
    epRed: Prefab

    @property({
        type: Prefab
    })
    epYellow: Prefab;

    @property({
        type: Prefab
    })
    epBlue: Prefab;

    @property
    spRateRed: number = 1;

    @property
    spRateYellow: number = 1;

    @property
    spRateBlue: number = 1;

    @property
    timeBtEnemySpawn: number = 2;

    @property({
        type: [Node]
    })
    areas: Array<Node> = [];

    areaRectLst: Array<Size>;

    spawnerTimer: number = 0;

    onLoad() {
        this.areaRectLst = new Array<Size>(this.areas.length);
        let gameLayer = GameMgr.inst.gameLayer.getComponent(UITransform);
        
        for(let i = 0; i < this.areas.length; i++) {
            let uiTransform = this.areas[i].getComponent(UITransform);
            gameLayer.convertToNodeSpaceAR(uiTransform.convertToWorldSpaceAR(Vec3.ZERO, outPos), outPos);
            let areaSize = this.areaRectLst[i] = rect();
            areaSize.x = outPos.x - uiTransform.width * 0.5;
            areaSize.y = outPos.y - uiTransform.height * 0.5;
            areaSize.width = uiTransform.width;
            areaSize.height = uiTransform.height;
        }

        this.spawnerTimer = this.timeBtEnemySpawn;
    }

    update(dt: number) {
        this.spawnerTimer += dt;
        if(this.spawnerTimer >= this.timeBtEnemySpawn && GameMgr.inst.gameActive) {
            this.spawnerTimer -= this.timeBtEnemySpawn;
            this.spawnEnemy();
            this.updateEnemyRate();
        }
    }

    spawnEnemy() {
        let idx = Math.floor(this.areaRectLst.length * Math.random());
        let areaSize = this.areaRectLst[idx];
        outPos.x = areaSize.x + areaSize.width * Math.random();
        outPos.y = areaSize.y + areaSize.height * Math.random();
        outPos.z = 0;
        let preafab = this.getEnemy2Spawn();
        let node = ObjPool.getNode(preafab.data.name, preafab);
        node.parent = GameMgr.inst.gameLayer;
        node.setPosition(outPos);
    }

    getEnemy2Spawn() {
        let total = this.spRateRed + this.spRateBlue + this.spRateYellow;
        let radNum = Math.random() * total;
        if(radNum <= this.spRateRed) {
            return this.epRed;
        }
        else if(radNum <= this.spRateBlue + this.spRateRed) {
            return this.epBlue;
        }
        else {
            return this.epYellow;
        }
    }

    updateEnemyRate() {
        this.spRateRed += 0.05;
        this.spRateYellow += 0.03;
        this.spRateBlue += 0.03;
    }
}