import CtrlBase from './CtrlBase';
import Player from './Player';
import TiledMapCtrl from '../TiledMapCtrl';
import PlayerMgr from '../PlayerMgr';
import BubbleMgr from '../BubbleMgr';
import ItemMgr from '../ItemMgr';
import ModuleMgr from '../../Module/ModuleMgr';
export default class MoveCtrl extends CtrlBase {
    public velocity: cc.Vec2 = cc.v2(0, 0);
    constructor(owner: Player) {
        super(owner);
    }

    onUpdate(dt: number) {
        //
        if (this.velocity.x === 0 && this.velocity.y === 0) {
            return;
        }
        if (!this.checkCollic()) {
            let offset = this.velocity.mul(dt);
            this.owner.node.x += offset.x;
            this.owner.node.y += offset.y;
            this.owner.refreshZIndex();
        }
    }

    checkCollic() {
        let dir = this.velocity.normalize();
        let collicTile = this.owner.getCollicTile(dir);
        let tiledMapCtrl = <TiledMapCtrl>ModuleMgr.getInstance().getModule('TiledMapCtrl');
        let bubbleMgr = <BubbleMgr>ModuleMgr.getInstance().getModule('BubbleMgr');
        if (tiledMapCtrl.checkOutOf(collicTile)) {
            return true;
        }

        //有没有碰到泡泡(玩家所在的格子没有泡泡，碰撞点所在的格子有泡泡)
        if (!bubbleMgr.getBubbleByTile(this.owner.getTile()) && bubbleMgr.getBubbleByTile(collicTile)) {
            return true;
        }
        //判断有没有碰到道具
        let itemMgr = <ItemMgr>ModuleMgr.getInstance().getModule('ItemMgr');
        let ownerTile = this.owner.getTile();
        let itemJs = itemMgr.getItemByTile(ownerTile);
        if (itemJs) {
            this.owner.eatItem(itemJs);
            itemMgr.removeItemByTile(ownerTile);
        }
        let tileInfo = tiledMapCtrl.getTiledInfo(collicTile);
        if (!tileInfo) {
            return false;
        }
        if (tileInfo.push) {
            //推箱子
            if (this._canPush(collicTile, dir)) {
                tiledMapCtrl.pushBox(collicTile, dir);
            }

            return true;
        }
        if (!tileInfo.colli) {
            return false;
        }

        return true;
    }

    _canPush(tile: cc.Vec2, dir: cc.Vec2) {
        let tiledMapCtrl = <TiledMapCtrl>ModuleMgr.getInstance().getModule('TiledMapCtrl');
        let playerMgr = <PlayerMgr>ModuleMgr.getInstance().getModule('PlayerMgr');
        let nextTile = cc.v2(tile.x + dir.x, tile.y - dir.y);
        if (tiledMapCtrl.checkOutOf(nextTile)) {
            return false;
        }
        let nextTileInfo = tiledMapCtrl.getTiledInfo(nextTile);
        //有没有地图上的其他障碍物
        if (nextTileInfo && nextTileInfo.colli) {
            return false;
        }
        //有没有玩家
        if (playerMgr.getPlayerByTile(nextTile)) {
            return false;
        }
        //有没有泡泡
        let bubbleMgr = <BubbleMgr>ModuleMgr.getInstance().getModule('BubbleMgr');

        return !bubbleMgr.getBubbleByTile(nextTile);
    }
}