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

public class Tower : MonoBehaviour
{
    public Animation catapultPivotAnim;
    public Animation armPivotAnim;
    public Animation crankAnim;
    public Transform platformTransform;
    public Transform gearTransform;
    public Transform launchPointTransform;
    public GameObject bulletPrefab;
    public LayerMask targetingLayerMask;

    private GameObject currentTarget;
    private float targetingRange;
    private bool turningAllowed;
    private bool firingAllowed;
    private float turnspeed;

    private void Awake()
    {
        firingAllowed = true;
        turningAllowed = true;
        currentTarget = null;
        targetingRange = 100.0f;
        turnspeed = 1.1f;
    }

    private void Start()
    {

    }

    private void Update()
    {
        //Target closest in range
        if (currentTarget == null)
        {
            Collider[] targets = Physics.OverlapSphere(transform.position, targetingRange, targetingLayerMask);
            float leastSqDist = targetingRange * targetingRange;
            foreach (Collider target in targets)
            {
                Vector3 targetPos = target.transform.position;
                float sqDist = Vector3.SqrMagnitude(targetPos - transform.position);
                if (sqDist < leastSqDist)
                {
                    leastSqDist = sqDist;
                    currentTarget = target.gameObject;
                }
            }
        }

        if (currentTarget != null)
        {
            //Fire
            Vector3 targetPos = currentTarget.transform.position;
            Vector3 targetDir = targetPos - platformTransform.position;
            targetDir.y = 0.0f;
            float angle = Vector3.Angle(platformTransform.forward, targetDir);
            if (angle <= 0.5f)
            {
                if (firingAllowed)
                {
                    StartCoroutine("Fire");
                }
            }
            else if (turningAllowed)
            {
                //Turn gear
                float d = Vector3.Dot(platformTransform.transform.right, targetPos - transform.position);
                float gearSpeed = turnspeed * 2.0f * Time.deltaTime * Mathf.Rad2Deg;
                bool clockwise = (d < 0.0f);
                if (clockwise)
                {
                    gearSpeed = -gearSpeed;
                }
                gearTransform.Rotate(0.0f, 0.0f, gearSpeed);

                //Turn platform
                float t = Mathf.Min(turnspeed * Time.deltaTime, 1.0f);
                Vector3 forward = platformTransform.forward;
                Vector3 newDir = Vector3.RotateTowards(forward, targetDir, t, 0.0f);
                platformTransform.rotation = Quaternion.LookRotation(newDir);
            }
        }
    }

    private IEnumerator Fire()
    {
        firingAllowed = false;
        turningAllowed = false;

        armPivotAnim.Stop();
        armPivotAnim.Play("ArmPivot", PlayMode.StopAll);
        yield return new WaitForSeconds(0.0835f);

        Vector3 position = launchPointTransform.position;
        Quaternion rotation = launchPointTransform.rotation;
        GameObject bullet = Instantiate(bulletPrefab, position, rotation) as GameObject;
        Rigidbody rb = bullet.GetComponent<Rigidbody>();
        rb.AddForce(bullet.transform.forward * 120.0f);
        catapultPivotAnim.Play("CatapultPivot", PlayMode.StopAll);
        yield return new WaitForSeconds(0.25f);

        crankAnim.Stop();
        crankAnim.Play("CrankTurn", PlayMode.StopAll);

        yield return new WaitForSeconds(0.4f);
        turningAllowed = true;
        yield return new WaitForSeconds(0.9f);
        firingAllowed = true;
        yield break;
    }
}
