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

public class UnitController : MonoBehaviour {

    public float Speed = 5;
    public float TurnRate = 500;
    public float SoundFrequency;

    public LevelController Level;

    string ActiveSound;
    float NextSound;


    // Use this for initialization
    void Start () {
        NextSound = Time.time + SoundFrequency;
	}

	// Update is called once per frame
	void Update () {
        var position = transform.position;
        var localTower = GetNearestTower(position);
        var target = GetTargetWaypoint(localTower);

		//Check to see if close to end tower
		var targetTower = Level.Target.GetComponentInChildren<TowerController>();
		var tDistance = (targetTower.Position - position).sqrMagnitude;
		if (tDistance < 0.5) {
			GameController.Current.SetView(GameController.Views.Win);
			return;
		}

		//Get distance to target
        var vector = target - position;
        var dist = vector.sqrMagnitude;

        if (dist > 0.5)
        {
            var turn = Vector3.RotateTowards(transform.forward, vector, TurnRate * Time.deltaTime, 0);
            transform.rotation = Quaternion.LookRotation(turn);
            gameObject.transform.Translate(0, 0, Speed * Time.deltaTime, Space.Self);
        }
        if (Time.time > NextSound)
        {
            SoundController.Current.PlaySound(ActiveSound);
            NextSound += SoundFrequency;
        }
    }

    TowerController GetNearestTower(Vector3 position)
    {
        return Level.GetNearestTower(position);
    }
    Vector3 GetTargetWaypoint(TowerController current)
    {
        if (current.Active)
        {
            if (current.ActiveChild != null)
            {
                ActiveSound = SoundController.Advance;
                return current.ActiveChild.Position;
            }
            else
            {
                ActiveSound = SoundController.Arrived;
                return current.Position;
            }
        }
        else
        {
            ActiveSound = SoundController.Backtrack;
            return current.Parent.Position;
        }
    }
}
