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

import {ScillaEvent, Texture,} from "scilla";
import TouchZoom from "../animation/TouchZoom";
import {InteractComponent} from "../base";
import {TextureRenderer} from "../renderer";

export default class Button extends InteractComponent {
	upRes: Texture;
	downRes: Texture;
	disabledRes: Texture;
	onClick: ScillaEvent;

	private bgRenderer: TextureRenderer;
	private currentRes: Texture;
	private touchBeginWithSelf: boolean;
	private touchOut: boolean;

	constructor() {
		super();

		this.touchInterrupt = true;
	}

	get touchZoom(): TouchZoom{
		return this.entity && this.entity.getComponent(TouchZoom);
	}

	onModify(value, key, oldValue) {
		super.onModify(value, key, oldValue);

		if (key === 'interactable') {
			if(this.touchZoom){
				this.touchZoom.interactable = value;
			}
			try {
				this.changeTexture();
			}catch (e) {}
		}
	}

	onCreate() {
		super.onCreate();

		this.onClick = new ScillaEvent();
	}

	onAwake() {
		super.onAwake();

		this.bgRenderer = this.entity.getComponent(TextureRenderer);

		this.changeTexture(this.upRes);
	}

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

		this.touchBeginWithSelf = true;

		this.changeTexture(this.downRes);
	}

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

		if (this.touchBeginWithSelf) {
			this.touchBeginWithSelf = true;
			this.changeTexture(this.downRes);
		}
		this.touchOut = false;
	}

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

		if (this.touchBeginWithSelf) {
			this.changeTexture(this.upRes);
		}
		this.touchOut = true;
	}

	onGlobalTouchEnd(e) {
		super.onGlobalTouchEnd(e);

		if (this.touchBeginWithSelf && !this.touchOut) {
			this.onClick.invoke();
		}

		this.touchBeginWithSelf = false;
		this.changeTexture(this.upRes);
	}

	changeTexture(res?) {
		if(!this.bgRenderer){
			return;
		}

		this.currentRes = res || this.upRes;
		if(this.interactable){
			this.bgRenderer.texture = this.currentRes;
		}else{
			this.bgRenderer.texture = this.disabledRes;
		}
	}
}
