using UnityEngine;
using UnityEngine.UI;
using System;

public class CustomFadeMaterial : MonoBehaviour {

    private int material_TexLerp;
	private Material material;
	private Coroutine coroutine;
	private SpriteRenderer spriteRenderer;

    private Action changeCallback = ActionExtensions.EmptyAction;
    void Awake(){
        material_TexLerp = Shader.PropertyToID("_TexLerp");
		transform.FindComponent<Image>(image => material = image.material);
		transform.FindComponent<SpriteRenderer>(sr => {
			spriteRenderer = sr;
			material = sr.material;
		});
    }

    public void Change(Sprite sprite, float duration){
        Change(sprite, duration, ActionExtensions.EmptyAction);
    }
    public void Change(Sprite sprite, float duration, Action callback){
        this.SafeStopCoroutine(coroutine);
        if(gameObject.activeInHierarchy){
            material.SetTexture("_SubTex", sprite.texture);
            float from = material.GetFloat(material_TexLerp);
            changeCallback = () => {
                changeCallback = ActionExtensions.EmptyAction;
                material.SetTexture("_MainTex", sprite.texture);
                material.SetFloat(material_TexLerp, 0.0f);
                if(spriteRenderer != null) spriteRenderer.sprite = sprite;
                callback(); // HACK ここでcallbackを呼ぶか、CallLerpSmoothのcallbackでcallbackを呼ぶか…
            };
            coroutine = this.CallLerpSmooth(duration, lerp => {
                material.SetFloat(material_TexLerp, Mathf.Lerp (from, 1.0f, lerp));
            }, changeCallback);
        }else{
            Change(sprite);
            callback();
        }
    }

    public void ChangeImmidiate(Sprite sprite){
        this.SafeStopCoroutine(coroutine);
        Change(sprite);
    }

    private void Change(Sprite sprite){
        material.SetTexture("_SubTex", sprite.texture);
        material.SetTexture("_MainTex", sprite.texture);
        if(spriteRenderer != null) spriteRenderer.sprite = sprite;
    }

    void OnDisable(){
        this.SafeStopCoroutine(coroutine);
        changeCallback();
    }

#if UNITY_EDITOR
	void OnDestroy(){
		material.SetTexture("_SubTex", null);
		material.SetTexture("_MainTex", null);
		material.SetFloat(material_TexLerp, 0.0f);
	}
#endif
}
