﻿using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RERTFollower : MonoBehaviour
{
    private List<Vector3> navigationList = new List<Vector3>();
    public Transform target;
    public float speed = 10;
    public float rangeToMoveOn = 1.5f;
    public float lastCost;
    private CharacterController charControl;

    public virtual void OnDrawGizmos()
    {
        if (!Application.isEditor) return;
        Gizmos.color = Color.yellow;
        if (navigationList.Count > 0)
        {
            for (int i = 0; i < navigationList.Count; i++)
            {
                Gizmos.DrawSphere(navigationList[i], Mathf.Max(0.1f,0.1f*i));
            }
            for (int i = 0; i < navigationList.Count - 1; i++)
            {
                Gizmos.DrawLine(navigationList[i], navigationList[i+1]);
            }
        }
    }

    [Button]
    public void GetPath()
    {
        Debug.Log(RERTManager.Instance);
        RERTManager.Instance.SetupRequest(transform.position,target.position,ReceiveNewPath);
    }

    private void ReceiveNewPath(RertRequest obj)
    {
        navigationList.Clear();
        for (int i = 0; i < obj.pathResult.Count; i++)
        {
            navigationList.Add(obj.pathResult[i]);
        }
        lastCost = obj.pathCost;
    }

    // Use this for initialization
	void Start ()
	{
	    charControl = GetComponent<CharacterController>();
	    gameObject.GetComponentInChildren<MeshRenderer>().material.color = Color.blue;
	}
	
	// Update is called once per frame
	void FixedUpdate () {
	    if (navigationList.Count > 0)
	    {
	        Vector3 desiredPos = navigationList[navigationList.Count-1];

            charControl.SimpleMove((desiredPos - transform.position).normalized * Time.deltaTime * 50* speed);
	        if (RERTManager.Instance.IsInRange(desiredPos, transform.position, rangeToMoveOn))
	            navigationList.RemoveAt(navigationList.Count - 1);
	    }
	}
}
