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

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

    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;
    private float Screenfactor;
    
    // Start is called before the first frame update
    void Start()
    {
        pathName = _pathUI.transform.GetComponentInChildren<Text>();
        _pathUI.SetActive(false);
        middlePoint = _pathUI.transform.position;
        Screenfactor = Screen.width / 862.0f * 2.5f; // ratio of Screen size-original size (match with width)
                                                     // 862 is player camera width-size
                                                     // 2.5 is ratio of UI-GameObject size (match width width)
    }

    // 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))
            {
                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 + (square.GetDestPoint(pathNum) + new Vector3(0, 300, 0)) * Screenfactor;
                        _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;
        }
    }
}
