/**
 * Created by rockyl on 2019-05-07.
 *
 * 游戏舞台
 */

import ScillaComponent from "components/base/ScillaComponent";
import {Entity, instantiate, Texture, resource, dynamic, engine} from "scilla";
import Miner from "./Miner";
import BottomButtonController from "./BottomButtonController";
import CountDown from "../common/CountDown";
import ItemLayer from "./ItemLayer";
import globalEvent from "globalEvent";

const minerConfigs = [
	{res: 'blue', dir: 1, walk: true},
	{res: 'red', dir: -1, walk: false},
];

export default class GameStage extends ScillaComponent {
	MinerLayer: Entity;
	ItemLayer: Entity;
	Bottom: Entity;
	CountDown: Entity;

	isLogin: dynamic;

	holeRes: Texture;
	minerPrefab: resource;
	activityBaseInfo: dynamic;
	singleDigData: dynamic;
	pkDigData: dynamic;

	private _bottomButtonController: BottomButtonController;
	private _miners: Miner[] = [];
	private _countdown: CountDown;
	private _itemLayer: ItemLayer;
	private _orderStatus;
	private _digFinishedCount;
	private _minerCount;

	onCreate() {
		super.onCreate();

		this._bottomButtonController = this.Bottom.getComponent(BottomButtonController);
		this._countdown = this.CountDown.getComponent(CountDown);
		this._itemLayer = this.ItemLayer.getComponent(ItemLayer);

		for (let config of minerConfigs) {
			let minerEntity = instantiate(this.minerPrefab);
			this.MinerLayer.addChild(minerEntity);

			let miner: Miner = minerEntity.getComponent(Miner);
			miner.prepare(this._itemLayer.digDelegate, this.holeRes.height - 40, config.res);
			this._miners.push(miner);

			minerEntity.enabled = false;
		}

	}

	initGameStage() {
		this.reset();

		if (this.activityBaseInfo.machineNickname) {
			this.bubbling('showDialog', 'PKChallenge', null, this.onPKChallengeClose)
		}
	}

	private reset() {
		for (let miner of this._miners) {
			miner.entity.enabled = false;
			miner.reset();
		}
		this._itemLayer.prepareItems();
		this.resetBottomButton();

		const selfMiner: Miner = this._miners[0];
		selfMiner.entity.enabled = true;
		selfMiner.standSide(1);
		selfMiner.playWalk();
	}

	resetBottomButton() {
		this._bottomButtonController.switchState(false);
		this._bottomButtonController.enableAll();
	}

	private loginAlert() {
		if (!this.isLogin) {
			this.bubbling('showLoginAlert');
		}

		return this.isLogin;
	}

	private creditsAlert() {
		/*let {miningExpend, pkExpend, curCredits} = engine.dataCenter.get('API', 'activityBaseInfo');

		if (miningExpend > curCredits || pkExpend > curCredits) {
			this.bubbling('showCreditsAlert');

			return false;
		}*/

		return true;
	}

	onTapDig() {
		if (!this.loginAlert() || !this.creditsAlert()) {
			return;
		}
		this._bottomButtonController.disableAll();

		this._orderStatus = 0;
		this._digFinishedCount = 0;
		this._minerCount = 1;

		const opActivityId = engine.dataCenter.get('CFG', 'opActivityId');
		this.broadcast('callApi', 1, 'singleDigData', {opActivityId})
	}

	onTapPK(channel = 0) {
		if (!this.loginAlert() || !this.creditsAlert()) {
			return;
		}
		this._bottomButtonController.disableAll();

		this._orderStatus = 0;
		this._digFinishedCount = 0;
		this._minerCount = 2;

		const opActivityId = engine.dataCenter.get('CFG', 'opActivityId');
		this.broadcast('callApi', 1, 'pkDigData', {opActivityId}, channel)
	}

	changeOrderStatus(v) {
		this._orderStatus = v;
		this.checkDigEnd();
	}

	readyDig(minerCount, channel) {
		if (minerCount === 1) {
			this.startDig(minerCount);
		} else {
			//this.onDigEnd();
			if(channel === 1){
				this.pkDigData.machineNickname = this.activityBaseInfo.machineNickname;
			}
			this.bubbling('hideAllDialog');
			this.bubbling('showDialog', 'PKMatching', {channel}, this.matchResult);
		}

		this.activityBaseInfo.curCredits -= minerCount === 1 ? this.activityBaseInfo.miningExpend : this.activityBaseInfo.pkExpend;
		globalEvent.emit('runCredits', 500);

		this._itemLayer.stopCreditsAnimation();
	}

	startDig(minerCount) {
		const {_miners, _countdown} = this;

		_countdown.stop();

		const selfMiner: Miner = _miners[0];
		selfMiner.playDig();
		if (minerCount === 1) {

		} else {
			this._bottomButtonController.disablePkDigButton();
			const otherMiner: Miner = _miners[1];
			otherMiner.avoidToDig(selfMiner.transform.position);
		}
	}

	private matchResult = (action) => {
		if (action === 'close') {
			this._bottomButtonController.enableAll();
			this.broadcast('abortCallApi', 1, 'getOrderStatus');
		} else {
			this.startPKDig();
		}
	}

	startPKDig() {
		this._bottomButtonController.switchState(true);
		this._countdown.play();

		for (let i = 0, li = minerConfigs.length; i < li; i++) {
			const config = minerConfigs[i];
			const miner = this._miners[i];

			miner.entity.enabled = true;
			miner.standSide(config.dir);
			miner.playWalk();
		}
	}

	restoreDig(e) {
		this.reset();
	}

	checkDigEnd() {
		if (this._orderStatus !== 0 && this._digFinishedCount === this._minerCount) {
			switch (this._orderStatus) {
				case 2:
				case 4:
					this.onDigEnd();
					break;
				case 1:
				case 3:
					this.bubbling('showNetError');
					break;
			}
		}
	}

	digEnd() {
		this._digFinishedCount++;
		this.checkDigEnd();
	}

	private onDigEnd() {
		switch (this._minerCount) {
			case 1:
				this.activityBaseInfo.curCredits += this.singleDigData.finalCredits;
				this.activityBaseInfo.heapCredits += this.singleDigData.finalCredits;

				this.bubbling('hideAllDialog');
				this.bubbling('showDialog', 'SingleResult', null, this.onSingleResultComplete);
				break;
			case 2:
				const {userFinalCredits, machineFinalCredits} = this.pkDigData;
				const resultState = userFinalCredits === machineFinalCredits ? 0 : (userFinalCredits > machineFinalCredits ? -1 : 1);
				this.pkDigData.resultState = resultState;

				let gotCredits = userFinalCredits;
				if (resultState < 0) {
					gotCredits += machineFinalCredits;
				} else if (resultState > 0) {
					gotCredits = 0;
				}

				this.activityBaseInfo.curCredits += gotCredits;
				this.activityBaseInfo.heapCredits += gotCredits;

				this.bubbling('hideAllDialog');
				this.bubbling('showDialog', 'PKResult', null, this.onPKResult);
				break;
		}
	}

	private onPKResult = (action) => {
		this.reset();

		if (action === 'retry') {
			this.onTapPK();
		}
	}

	private onSingleResultComplete = () => {
		this.reset();

	}

	private onPKChallengeClose = (action) => {
		if(action === 'accept'){
			this.onTapPK(1);
		}
	}
}
