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

public class Evade : MonoBehaviour
{
    public GameObject WhiteSmoke;
    public GameObject m_target;
    public float m_turnSpeed = 0.75f;
    public float m_thrust = 5.0f;

    private Transform m_myTransform;
    private Transform m_targetTransform;
    private Vector3 m_lookLocation;
    private Quaternion m_lookRotation;
    private float m_retreatPositionZ;

    // sad, sad state machine
    private bool m_faceEnemyComplete = false;

    void Start()
    {
        m_myTransform = transform;
        m_targetTransform = m_target.transform;
    }

    void FixedUpdate()
    {
        if (!m_faceEnemyComplete)
        {
            float angle = Quaternion.Angle(m_myTransform.rotation, m_lookRotation);
            // turn to face the location to move to
            m_lookLocation = (m_targetTransform.position - m_myTransform.position).normalized;
            m_lookRotation = Quaternion.LookRotation(m_lookLocation);
            float m_step = m_turnSpeed * Time.deltaTime;
            m_myTransform.rotation = Quaternion.Slerp(m_myTransform.rotation, m_lookRotation, m_step);
            if (angle < 1.5f)
            {
                m_faceEnemyComplete = true;
                m_retreatPositionZ = transform.position.z + 50.0f;
                PopSmoke();
                PopSmoke();
            }
        }
        else
        {
            if (transform.position.z <= m_retreatPositionZ)
            {
                m_myTransform.Translate(-Vector3.forward * m_thrust * Time.deltaTime);
            }
        }
    }



    public Vector3 LerpByDistance(Vector3 A, Vector3 B, float x)
    {
        Vector3 P = x * Vector3.Normalize(B - A) + A;
        return P;
    }


    void PopSmoke()
    {
        Vector3 smokeLocation1 = LerpByDistance(transform.position, m_targetTransform.position, 10.0f);
        Vector3 location1 = transform.position + new Vector3(0, 0, -10) + Random.insideUnitSphere * 5;
        Instantiate(WhiteSmoke, smokeLocation1, Quaternion.identity);
        Instantiate(WhiteSmoke, location1, Quaternion.identity);
    }
}
