using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mapbox.Unity.Map;
using Mapbox.Examples;
using System;

public class GameManager : MonoBehaviour
{
    public GameObject[] waypoints;
    public AbstractMap map;
    public Canvas canvas;
    
    [SerializeField] Transform objA;
    [SerializeField] Transform objB;
    [SerializeField] int nbWaypoint = 0;
    [SerializeField] bool locked = false;
    private Vector3 offset;
    private Plane _yPlane;

    // Start is called before the first frame update
    void Start()
    {
        _yPlane = new Plane(Vector3.up, Vector3.zero);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0) && locked && nbWaypoint < 2)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            float enter = 0.0f;
            if (_yPlane.Raycast(ray, out enter))
            {
                Instantiate(waypoints[nbWaypoint], ray.GetPoint(enter), new Quaternion(0, 0, 0, 0));
                nbWaypoint++;
            }
        }
    }

    IEnumerator setRouteTracer()
    {
        bool repeat = false;
        try
        {
            objA = GameObject.FindGameObjectWithTag("start_wp").transform;
            objB = GameObject.FindGameObjectWithTag("end_wp").transform;

            //gameObject.AddComponent<RouteTracer>();
        }
        catch (NullReferenceException)
        {
            repeat = true;
        }

        if (repeat)
        {
            yield return setRouteTracer();
        }

        yield return null;
    }

    // Lock la map
    public void lockMovement()
    {
        map.GetComponent<QuadTreeCameraMovement>().enabled = false;
        canvas.GetComponentInChildren<Transform>().gameObject.SetActive(false);
        locked = true;
    }
}