import { _decorator, Component, Node, Prefab, director, instantiate } from 'cc';
import { ApiMsgEnum, IMsgGameStart, IMsgRoom } from '../Common';
import { EventEnum, SceneEnum } from '../Enum';
import DataManager from '../Global/DataManager';
import EventManager from '../Global/EventManager';
import NetworkManager from '../Global/NetworkManager';
import { PlayerManager } from '../UI/PlayerManager';
const { ccclass, property } = _decorator;

@ccclass('RoomManager')
export class RoomManager extends Component {
    @property(Node)
    playerContainer: Node = null;

    @property(Prefab)
    playerPrefab: Prefab = null;

    onLoad() {
        director.preloadScene(SceneEnum.Battle);
        NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgRoom, this.renderPlayers);
        NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgGameStart, this.startGame);
    }

    onDestroy() {
        NetworkManager.Instance.unlistenMsg(ApiMsgEnum.MsgRoom, this.renderPlayers);
        NetworkManager.Instance.unlistenMsg(ApiMsgEnum.MsgGameStart, this.startGame);
    }

    async start() {
        this.renderPlayers({
            room: DataManager.Instance.roomInfo
        })
    }

    renderPlayers = ({ room: { players: list } }: IMsgRoom) => {
        for (const item of this.playerContainer.children) {
            item.active = false
        }
        while (this.playerContainer.children.length < list.length) {
            const playerItem = instantiate(this.playerPrefab);
            playerItem.active = false
            playerItem.setParent(this.playerContainer)
        }

        for (let i = 0; i < list.length; i++) {
            const data = list[i];
            const node = this.playerContainer.children[i]
            const playerItemManager = node.getComponent(PlayerManager)
            playerItemManager.init(data)
        }
    }

    async handleLeave() {
        const { success, res, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiRoomLeave, {});
        if (!success) {
            console.log(error)
            return;
        }

        DataManager.Instance.roomInfo = null
        director.loadScene(SceneEnum.Hall);
    }

    async handleStart() {
        const { success, res, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiGameStart, { rid: DataManager.Instance.roomInfo.id });
        if (!success) {
            console.log(error)
            return;
        }

        // director.loadScene(SceneEnum.Battle);
    }

    startGame = ({ state }: IMsgGameStart) => {
        DataManager.Instance.state = state

        director.loadScene(SceneEnum.Battle);
    }
}