/**
 * Created by rockyl on 2018/11/23.
 *
 * 按钮
 */

import {ScillaEvent, Texture, Entity, color, decorators} from "scilla";
import {InteractComponent} from "../base";
import {TextureRenderer} from "../renderer";
import TextRenderer from "../renderer/TextRenderer";

const {dirtyFieldDetector} = decorators;

enum STATUS {
	UP,
	DOWN,
	DISABLED,
}

export default class Button extends InteractComponent {
	@dirtyFieldDetector
	upRes: Texture;
	@dirtyFieldDetector
	downRes: Texture;
	@dirtyFieldDetector
	disabledRes: Texture;
	@dirtyFieldDetector
	Label: Entity;

	@dirtyFieldDetector
	upLabelColor: color;
	@dirtyFieldDetector
	downLabelColor: color;
	@dirtyFieldDetector
	disabledLabelColor: color;

	onClick: ScillaEvent = new ScillaEvent();

	touchInterrupt = true;

	private _bgRenderer: TextureRenderer;
	private _touchBeginWithSelf: boolean;
	private _touchOut: boolean;
	private _label: TextRenderer;

	onInteractableChanged(interactable) {
		const interactComponents = this.getComponents(InteractComponent);
		for (let interactComponent of interactComponents) {
			if (interactComponent !== this) {
				interactComponent.interactable = interactable;
			}
		}
		this.changeTexture();
	}

	onAwake() {
		super.onAwake();

		if(!this._bgRenderer){
			this._bgRenderer = this.getComponent(TextureRenderer);
			this._label = this.Label && this.Label.getComponent(TextRenderer);

			this.changeTexture(STATUS.UP);
		}
	}

	onUpdate(t) {
		super.onUpdate(t);

		if(this['dirty']){
			this.changeTexture();
			this['dirty'] = false;
		}
	}

	onTouchBegin(e) {
		super.onTouchBegin(e);

		this._touchBeginWithSelf = true;

		this.changeTexture(STATUS.DOWN);
	}

	onTouchOver(e) {
		super.onTouchOver(e);

		if (this._touchBeginWithSelf) {
			this._touchBeginWithSelf = true;
			this.changeTexture(STATUS.DOWN);
		}
		this._touchOut = false;
	}

	onTouchOut(e) {
		super.onTouchOut(e);

		if (this._touchBeginWithSelf) {
			this.changeTexture(STATUS.UP);
		}
		this._touchOut = true;
	}

	onGlobalTouchEnd(e) {
		if (this._touchBeginWithSelf && !this._touchOut) {
			this.onClick.invoke();
		}

		this._touchBeginWithSelf = false;
		this.changeTexture(STATUS.UP);

		return super.onGlobalTouchEnd(e);
	}

	changeTexture(status?: STATUS) {
		if (!this._bgRenderer) {
			return;
		}

		let res, labelColor;
		switch(status){
			case STATUS.UP:
				res = this.upRes;
				labelColor = this.upLabelColor;
				break;
			case STATUS.DOWN:
				res = this.downRes;
				labelColor = this.downLabelColor;
				break;
			case STATUS.DISABLED:
				res = this.disabledRes;
				labelColor = this.disabledLabelColor;
				break;
		}

		let currentRes = res || this.upRes;
		let currentColor = labelColor || this.upLabelColor;

		if (this.interactable) {
			this._bgRenderer.texture = currentRes;
			if(this._label){
				this._label.fillColor = currentColor;
			}
		} else {
			this._bgRenderer.texture = this.disabledRes;
			if(this._label){
				this._label.fillColor = this.disabledLabelColor;
			}
		}
	}
}
