
import { _decorator, Component, Node, Button, CCInteger } from 'cc';
import { Consts } from '../../Consts';
import { FightMapData } from '../../Fight/FightMapData';
import EventManager from '../../UIFrame/EventManager';
import { MoveDir } from '../../UIFrame/Types';
import { MapItem, MapItemType } from './MapItem';
const { ccclass, property } = _decorator;

@ccclass('FightMap')
export class FightMap extends Component {

    // 当前地图块 所在的整个地图的坐标
    x: number;
    y: number;

    // 切换地图按钮
    @property(Button) topButton: Button = null;
    @property(Button) bottomButton: Button = null;
    @property(Button) leftButton: Button = null;
    @property(Button) rightButton: Button = null;

    // 数据类
    fightMapData: FightMapData;

    start() {
        //TODO 检查所有物件的num, 有没有没设置的, 有没有设置重复了的

        this.topButton.node.active = false;
        this.bottomButton.node.active = false;
        this.leftButton.node.active = false;
        this.rightButton.node.active = false;
    }


    /**
     * 刷新 地图切换按钮的显示状态
     */
    refreshSwitchButton() {
        // 如果有怪, 则跳过
        for (let index = 0; index < this.node.children.length; index++) {
            const element = this.node.children[index];
            const mapItem = element.getComponent(MapItem);

            if (!mapItem) continue;
            console.log("  re. x=" + this.x + ", y=" + this.y);


            console.log(" re .. mapItem.type=" + mapItem.itemType + ", pro=" + mapItem.progress);
            if (mapItem.itemType == MapItemType.怪物) {
                if (mapItem.progress > 0)
                    return;
            }
        }
        // 没怪, 则显示
        let values = this.fightMapData.pathValue.split(",");
        this.topButton.node.active = (values[1] == "1");
        this.bottomButton.node.active = (values[2] == "1");
        this.leftButton.node.active = (values[3] == "1");
        this.rightButton.node.active = (values[4] == "1");

    }

    buttonGoTop() {
        EventManager.emit(Consts.FIGHT_MAP_MOVE, MoveDir.Up);
    }

    buttonGoBottom() {
        EventManager.emit(Consts.FIGHT_MAP_MOVE, MoveDir.Down);
    }

    buttonGoLeft() {
        EventManager.emit(Consts.FIGHT_MAP_MOVE, MoveDir.Left);
    }

    buttonGoRight() {
        EventManager.emit(Consts.FIGHT_MAP_MOVE, MoveDir.Right);
    }

    /**
     * 初始化数据
     */
    initData(mapData: FightMapData) {
        this.fightMapData = mapData;
        this.x = mapData.x;
        this.y = mapData.y;

        // 所有物件赋值
        if (mapData.dataMap.size == 0)
            return;
        for (let index = 0; index < this.node.children.length; index++) {
            const node = this.node.children[index];
            const mapItem = node.getComponent(MapItem);
            if (mapItem) {
                const num = mapItem.num;
                const progress = mapData.getItemValue(num);
                if (progress >= 0) {
                    mapItem.resetProgress(progress);
                }
            }
        }
    }
}