import ModuleBase from '../Module/ModuleBase'
import TiledMapCtrl from './TiledMapCtrl'
import Item from './Item'
import ResMgr from '../ResMgr'
import ConfigMgr from '../ConfigMgr'
export default class ItemMgr extends ModuleBase{
    private _itemParent:cc.Node = null;
    private _arrItem:Item [] = [];
    onInit(){
        this._itemParent = cc.find('Game/tileMap');
    }

    addItem(itemInfo){
        let prefab = ResMgr.getInstance().getPrefab('item');
        let itemN = cc.instantiate(prefab);
        itemN.parent = this._itemParent;
        let tileMapCtrl = <TiledMapCtrl>this.getModule('TiledMapCtrl');
        let pos = tileMapCtrl.getPosByTile(itemInfo.tile);
        let itemJs = <Item>itemN.getComponent('Item');
        itemJs.setPos(itemInfo.tile, pos);
        let config = ConfigMgr.getInstance().getData('ItemDt').getDataByID(itemInfo.itemID);
        itemJs.init(config);
        this._arrItem.push(itemJs);
    }

    getItemByTile(tile:cc.Vec2){
        for(let itemJs of this._arrItem){
            if(itemJs.tile.equals(tile)){
                return itemJs;
            }
        }
        return null;
    }

    removeItemByTile(tile:cc.Vec2){
        for(let i = 0; i < this._arrItem.length; i++){
            let itemJs = this._arrItem[i];
            if(itemJs.tile.equals(tile)){
                itemJs.node.destroy();
                this._arrItem.splice(i, 1);
                break;
            }
        }
    }
}