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

public class UIManager : MonoBehaviour
{
    [SerializeField]
    Square square;
    [SerializeField]
    Camera playercamera;

    public GameObject canvas;
    public Text mytime;
    //public Planemovement clock1;
    //public Planemovement clock2;
    //public Text clock1time;
    //public Text clock2time;
    public Text wintext;
    public GameObject _pathUI;
    public LevelManager Levelmanager;
    private int prevSelectPathNum = -1;
    private Text pathName;
    private Vector3 middlePoint;
    
    // Start is called before the first frame update
    void Start()
    {
        _pathUI.SetActive(false);
        pathName = _pathUI.transform.Find("Name").GetComponent<Text>();
        middlePoint = _pathUI.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        mytime.text = Levelmanager.player.time.ToString() + " s";
        //clock1time.text = clock1.GetTime().ToString() + " s";
        //clock2time.text = clock2.GetTime().ToString() + " s";
        if(Levelmanager.winstate)
        {
            wintext.gameObject.SetActive(true);
        }
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            
            if (Physics.Raycast(ray, out hit))
            {
                ray = playercamera.ViewportPointToRay(hit.textureCoord);
                if (Physics.Raycast(ray, out hit))
                {
                    var obj = hit.collider.gameObject;

                    if (obj.tag == "path")
                    {
                        int pathNum = int.Parse(obj.name.Substring(13));

                        if (pathNum != prevSelectPathNum)
                        {
                            pathName.text = obj.name;
                            //_pathUI.transform.position = middlePoint;
                            _pathUI.transform.position = middlePoint + (square.GetDestPoint(pathNum) + new Vector3(0, 300, 0)) * 2.5f;
                            //Debug.Log(square.GetMiddlePoint(pathNum, pathNum + 1));
                            _pathUI.SetActive(true);
                            prevSelectPathNum = pathNum;
                        }
                        else
                        {
                            _pathUI.SetActive(false);
                            prevSelectPathNum = -1;
                        }
                    }
                    else
                    {
                        _pathUI.SetActive(false);
                        prevSelectPathNum = -1;
                    }
                }
            }
        }
        else if (Input.GetMouseButtonDown(1))
        {
            _pathUI.SetActive(false);
            prevSelectPathNum = -1;
        }
    }
}
