/**
 * Created by rockyl on 2019-05-09.
 *
 * 底部按钮控制器
 */

import ScillaComponent from "components/base/ScillaComponent";
import {dynamic, Entity} from "scilla";
import TwoLinesButton from "../game/TwoLinesButton";
import Wave from "components/animation/Wave";
import WaveController from "../common/WaveController";
import {renderRunCredits} from "./utils";
import CustomButton from "./CustomButton";

function getWaveAlgorithm(){
	return function bounce(t){
		const s = 1 + Math.abs(Math.sin(t)) * 0.1;

		return {
			sx: s,
			sy: s,
		}
	}
}

export default class BottomButtonController extends ScillaComponent {
	activityBaseInfo: dynamic;
	buttonPKEntity: Entity;
	buttonDigEntity: Entity;
	buttonDigSLEntity: Entity;

	private _buttonPK: TwoLinesButton;
	private _buttonDig: TwoLinesButton;
	private _buttonSLDig: CustomButton;

	private _buttons = [];
	private _counting = 0;

	onAwake() {
		super.onAwake();

		this._buttonSLDig = this.buttonDigSLEntity.getComponent(CustomButton);

		this._buttonPK = this.buttonPKEntity.getComponent(TwoLinesButton);
		const wavePK = this.buttonPKEntity.getComponent(Wave);
		const wcPK = this.buttonPKEntity.getComponent(WaveController);
		wavePK.waveAlgorithm = getWaveAlgorithm();

		this._buttonDig = this.buttonDigEntity.getComponent(TwoLinesButton);
		const waveDig = this.buttonDigEntity.getComponent(Wave);
		const wcDig = this.buttonDigEntity.getComponent(WaveController);
		waveDig.waveAlgorithm = getWaveAlgorithm();

		this.switchState(false);

		this._buttons.push({
			button: this._buttonPK,
			wave: wavePK,
			wc: wcPK,
		}, {
			button: this._buttonDig,
			wave: waveDig,
			wc: wcDig,
		});

		setInterval(()=>{
			const {button, wave, wc} = this._buttons[(this._counting++) % this._buttons.length];
			if(button.interactable && !wc.touchBeginFlag){
				wave.play();
			}
		}, 600);

		this.updateButtonLabel();
		this.disableAll();
	}

	initGameStage(){
		const {pkExpend, miningExpend} = this.activityBaseInfo;

		this.updateButtonLabel(pkExpend, miningExpend);
		this.switchState(false);
	}

	private updateButtonLabel(pkExpend = 0, miningExpend = 0){
		this._buttonPK.label1 = renderRunCredits(pkExpend) + '/次';
		this._buttonDig.label1 = renderRunCredits(miningExpend) + '/次';
	}

	enableAll(){
		for(let {button, wc} of this._buttons){
			button.interactable = true;
			wc.touchBeginFlag = false;
		}
	}

	disableAll(){
		for(let {button, wc} of this._buttons){
			button.interactable = false;
			wc.touchBeginFlag = false;
		}
	}

	enablePkDigButton(){
		this._buttonSLDig.interactable = true;
	}

	disablePkDigButton(){
		this._buttonSLDig.interactable = false;
	}

	switchState(isPK){
		this.buttonPKEntity.enabled = !isPK;
		this.buttonDigEntity.enabled = !isPK;

		this.buttonDigSLEntity.enabled = isPK;

		if(isPK){
			this.enablePkDigButton();
		}
	}
}
