
import { _decorator, Component, Node, Prefab, instantiate, Camera, Collider } from 'cc';
import { IArea, ICountry, IMap, IPlayer } from '../../../shared/gameClient/games/OccupationTheWarModels';
import { PHY_GROUP } from '../Const';
import { OTWAreaFlagComponent } from './OTWAreaFlagComponent';
import { OTWAreaData } from '../Data/OTWAreaData';
import { OTWGameData } from '../Data/OTWGameData';
import { OTWObjectComponent } from './OTWObjectComponent';
import { OTWFlagComponent } from './OTWFlagComponent';
const { ccclass, property } = _decorator;

@ccclass('OTWAreaComponent')
export class OTWAreaComponent extends OTWObjectComponent {
    areaInfo!: OTWAreaData;

    start() {
        var collider = this.getComponentInChildren(Collider);
        collider?.setGroup(PHY_GROUP.Area);
        collider?.setMask(0xffffffff);
    }

    public updateData(dt: number) {
        if ( this.areaInfo.area.troopsCurr < this.areaInfo.area.troopsMax) {
            //增兵
            this.areaInfo.area.troopsCurrCalculate += this.areaInfo.area.troopsInc * dt;
            if (this.areaInfo.area.troopsCurrCalculate > this.areaInfo.area.troopsMax) {
                this.areaInfo.area.troopsCurrCalculate = this.areaInfo.area.troopsMax;
            }
            var curr = Math.floor(this.areaInfo.area.troopsCurrCalculate);
            if (curr > this.areaInfo.area.troopsCurr) {
                this.areaInfo.area.troopsCurr = curr;
                this.areaInfo.flagComp.updateShow();
            }
        }
    }

    public static createNode(areaPrefab: Prefab, areaFlagPrefab: Prefab,
        getGameData: () => OTWGameData, area: IArea, country: ICountry | null, mainCamera: Camera, gameMgrNode: Node,
        gameFlagUIWrapNode: Node, gameObjWrapNode: Node): OTWAreaData {


        var node = instantiate(areaPrefab);
        node.name = "Area_" + area.areaIndex;

        let flagComp!: OTWAreaFlagComponent;
        var flagNode = OTWFlagComponent.createFlagNode(OTWAreaFlagComponent, getGameData, areaFlagPrefab, node, mainCamera,
            gameMgrNode, "OTWGameManager", "onAreaFlagUIUpdate", area.areaIndex.toString(), country, (c) => {
                flagComp = c;
            });
        gameFlagUIWrapNode.addChild(flagNode);

        var areaComp = node.getComponent(OTWAreaComponent)!;
        areaComp.getGameData = getGameData;

        node.setPosition(area.x, 0, area.z);
        gameObjWrapNode.addChild(node);

        const areaInfo: OTWAreaData = {
            area: area,
            country: country,
            areaNode: node,
            areaComp: areaComp,
            flagNode: flagNode,
            flagComp: flagComp
        };
        flagComp.areaInfo = areaInfo;
        areaComp.areaInfo = areaInfo;

        flagComp.updateShow();

        return areaInfo;
    }
}
