using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class NumInfo : BattleWidgetInfo {

    public Color addColor = Color.green;
    public Color minusColor = Color.red;

    [SerializeField]
    Text numText;

    [SerializeField]
    AnimationCurve m_Curve;

    Vector3 m_TargetUVPos;

    // Use this for initialization
    protected override void Start () {
        gameObject.AddComponent<SelfDestroy>().lifeTime = 2;

       // var rect = GetComponent<RectTransform>();
       // StartCoroutine(PlayRectMove(m_Reference,3, m_TargetUVPos));
    }

    public void Init(int showNum,Transform refer,  Func<Vector3, Vector3, Vector3>worldToUIPosFunc, Vector3 targetUVPos,bool follow,bool moveUp,string pre = "+",Color color = new Color())
    {
        base.Init(refer, worldToUIPosFunc);

        m_TargetUVPos = targetUVPos;

        if (numText)
        {
            if (showNum >= 0)
            {
                numText.text = pre + string.Format("{0}", showNum);
                numText.color = this.addColor;
            }
            else
            {
                numText.text = string.Format("{0}", showNum);
                numText.color = this.minusColor;
            }
        }

        if (color.a > 0)
            numText.color = color;
        
        transform.position = this.m_WorldToUIPosFunc(refer.position, Vector3.zero);

        if (moveUp)
        {
            var rect = GetComponent<RectTransform>();
            StartCoroutine(PlayRectMove(m_Reference, 3, m_TargetUVPos,follow));
        }
        else if(follow)
        {
            StartCoroutine(UpdatePos(m_Reference));
        }
    }

    IEnumerator UpdatePos(Transform refer)
    {
        var rect = GetComponent<RectTransform>();
        while (true)
        {
            yield return 0;

            Vector3 targetPos = m_WorldToUIPosFunc(refer.transform.position, Vector3.zero);
            SetPosition(rect, targetPos);
        }
    }
    
    IEnumerator PlayRectMove(Transform refer, float time,Vector3 targetUVPos,bool follow)
    {
        if (m_WorldToUIPosFunc == null) yield break;

        float timer = 0;
        var rect = GetComponent<RectTransform>();

        while (timer <= time)
        {
            var pos = transform.position;
            if (follow)
                pos = m_WorldToUIPosFunc(refer.transform.position, Vector3.zero);
            
            Vector3 targetPos = pos + targetUVPos;// + new Vector3(0,300,0);
            targetPos.z = 10;
            timer += Time.deltaTime;

            float speed = m_Curve.Evaluate(timer / time);

            float y = Mathf.Lerp(transform.position.y, targetPos.y, 10 * speed * Time.deltaTime);
            var curPos = new Vector3(targetPos.x, y, 0);
            SetPosition(rect, curPos);
            yield return null;
        }

    }

}
