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

public class Character : MonoBehaviour
{
    private static List<int> TakenFingerIDs = new List<int>();

    public Color CharacterColour = Color.white;
    public float DragForceMultiplier = 5;
    public float ReleaseForceMultiplier = 2;

    [Range(0, 1)]
    public float ScreenFingerSizePercentage = 0.05f;
    public bool ShowGUI = false;

    private Vector2 ScreenPosition;
    private int FingerIndex = -1;
    private bool IsDown = false;
    private Vector2 TouchPosition;
    private Vector2 TouchReleasePosition;
    private Rigidbody2D RBody;

    public float Score
    {
        get;
        private set;
    }

    private void OnValidate()
    {
       
    }

    // Start is called before the first frame update
    void Start()
    {
        RBody = GetComponent<Rigidbody2D>();
    }

    private bool IsOver(Vector2 MousePosition)
    {
        float MaxDistance = Mathf.Min(Screen.width, Screen.height) * ScreenFingerSizePercentage;
        if (Vector2.Distance(MousePosition, ScreenPosition) < MaxDistance)
            return true;

        return false;
    }

    // Update is called once per frame
    void Update()
    {
        if (MasterUI.IsBusy)
        {
            gameObject.layer = LayerMask.NameToLayer("Character");
            return;
        }

        ScreenPosition = Camera.main.WorldToScreenPoint(transform.position);
        bool JustReleased = false;

        if (!IsDown)
        {
            if (Input.GetMouseButtonDown(0) && Input.touchCount <= 0)
            {
                if (IsOver(Input.mousePosition))
                {
                    if (!TakenFingerIDs.Contains(-1))
                    {
                        IsDown = true;
                        FingerIndex = -1;
                        TouchPosition = Input.mousePosition;
                        TakenFingerIDs.Add(FingerIndex);
                    }
                }
            }
            else
            {
                foreach(Touch touch in Input.touches)
                {
                    if (touch.phase == TouchPhase.Began)
                    {
                        if (IsOver(touch.position))
                        {
                            if (!TakenFingerIDs.Contains(touch.fingerId))
                            {
                                IsDown = true;
                                FingerIndex = touch.fingerId;
                                TouchPosition = touch.position;
                                TakenFingerIDs.Add(FingerIndex);
                                break;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            if (FingerIndex == -1)
            {
                if (Input.GetMouseButtonUp(0))
                {
                    TouchPosition = Input.mousePosition;
                    IsDown = false;
                    JustReleased = true;
                    TakenFingerIDs.Remove(FingerIndex);
                }
                else if(Input.GetMouseButton(0))
                {
                    TouchPosition = Input.mousePosition;
                }
            }
            else
            {
                foreach (Touch touch in Input.touches)
                {
                    if (touch.fingerId == FingerIndex)
                    {
                        if (touch.phase == TouchPhase.Canceled || touch.phase == TouchPhase.Ended)
                        {
                            TouchPosition = touch.position;
                            IsDown = false;
                            JustReleased = true;
                            TakenFingerIDs.Remove(FingerIndex);
                        }
                        else if(touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
                        {
                            TouchPosition = Input.mousePosition;
                        }
                    }
                }
            }
        }

        Vector3 DesiredWorldPosition = Camera.main.ScreenToWorldPoint(TouchPosition);
        DesiredWorldPosition.z = 0;

        RBody.gravityScale = IsDown ? 0 : 1;

        if (IsDown)
        {
            RBody.velocity = (DesiredWorldPosition - transform.position) * DragForceMultiplier;
            //RBody.position = Vector3.Lerp(RBody.position, DesiredWorldPosition, Time.smoothDeltaTime * DragForceMultiplier);
            //RBody.AddForce((DesiredWorldPosition - transform.position) * DragForceMultiplier, ForceMode2D.Impulse);
            //Debug.Log("Moving");
        }
        else if (JustReleased)
        {
            RBody.AddForce((DesiredWorldPosition - transform.position) * ReleaseForceMultiplier, ForceMode2D.Impulse);
            //Debug.Log("Released");
        }

        gameObject.layer = (IsDown ? LayerMask.NameToLayer("Character_Held") : LayerMask.NameToLayer("Character"));
    }

    public void AddScore(Vector3 Position, float Score)
    {
        if (Score < 1)
            Score = 1;

        //Show points at position
        this.Score += (int)Score;
        ScoreUI.AddScore(Position, (int)Score, CharacterColour);
    }

    private void OnGUI()
    {
        if(!ShowGUI)
            return;
        Rect R = new Rect(Vector2.zero, Vector3.one * (Mathf.Min(Screen.width, Screen.height) * ScreenFingerSizePercentage));
        if (IsDown)
            R.size *= 1.5f;
        R.center = new Vector2(ScreenPosition.x, Screen.height - ScreenPosition.y);
        GUI.color = CharacterColour;
        GUI.DrawTexture(R, Texture2D.whiteTexture, ScaleMode.StretchToFill);
    }
}
