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

public class CthulhuScript : MonoBehaviour
{
    [SerializeField]
    float p_mySpeed;
    [SerializeField]
    float p_myWalkTime;
    [SerializeField]
    float p_myLifeTime;
    [SerializeField]
    float p_myDistanceWithEarth;
    float p_myTimer;
    GameObject p_myEarth;
    [SerializeField]
    AudioSource p_myAudioSource;

    void Start()
    {
        p_myAudioSource = GameObject.FindGameObjectWithTag("Sound").transform.GetChild(2).GetComponent<AudioSource>();
        if (!p_myAudioSource.isPlaying)
        {
            p_myAudioSource.Play();
        }
        p_myEarth = GameObject.FindGameObjectWithTag("Earth");
        p_myTimer = RandomManager.getFloatRandom(p_myLifeTime);
        StartCoroutine(IACthulhu());
        StartCoroutine(LifeTime());
    }

    IEnumerator IACthulhu()
    {
        while (true)
        {
            float angle = RandomManager.getIntRandom(0, 360);
            float timer = 0;
            float forwardTime = RandomManager.getFloatRandom(p_myWalkTime);
            while (timer < forwardTime)
            {
                transform.LookAt(p_myEarth.transform.position);
                transform.position = transform.forward * -p_myDistanceWithEarth;
                transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, angle);
                timer += Time.deltaTime;
                transform.position += transform.right * p_mySpeed * Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }
        }
    }

    IEnumerator LifeTime()
    {
        yield return new WaitForSeconds(p_myTimer);
        Destroy(this.gameObject);
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Human")
        {
            collision.gameObject.GetComponent<HumanScript>().Death();
        }
        else if (collision.gameObject.tag == "Building")
        {
            collision.gameObject.GetComponent<BuildingScript>().Death();
        }
    }
}