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

public class ClickManager : MonoBehaviour {

    private static ClickManager _instance;
    public static ClickManager Instance
    {
        get
        {
            return _instance;
        }
    }

    public enum OrderCheck
    {
        Button
    }

    GameObject mObjectClicked;
    RaycastHit2D hit;

    private void Awake()
    {
        if(_instance == null)
        {
            _instance = this;
        }
        else
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1))
        {                        
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            CheckHit(ray);

            if (hit)
            {
                mObjectClicked = hit.collider.gameObject;
                mObjectClicked.GetComponent<IInteragable>().BtPressed();
            }
        }

        if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            CheckHit(ray);

            if (hit)
            {
                if(hit.collider.gameObject == mObjectClicked)
                {
                    mObjectClicked.GetComponent<IInteragable>().BtPressing();
                }else
                {
                    if (mObjectClicked != null)
                    {
                        mObjectClicked.GetComponent<IInteragable>().BtOutArea();
                    }
                }
            }
            else
            {
                if (mObjectClicked != null)
                {
                    mObjectClicked.GetComponent<IInteragable>().BtOutArea();
                }
            }
        }

        if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            CheckHit(ray);

            if (hit)
            {
                if (hit.collider.gameObject == mObjectClicked)
                {
                    mObjectClicked.GetComponent<IInteragable>().BtReleased();
                }
            }
            mObjectClicked = null;
        }
    }

    public void CheckHit(Ray ray)
    {
        hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, LayerMask.GetMask(OrderCheck.Button.ToString()));

        //if (!hit && mTouchInterface)
        //{
        //    hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, LayerMask.GetMask(OrderCheck.Button.ToString()));
        //}   
    }

}
