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

public class SpaceShipScript : MonoBehaviour
{
    GameObject p_myEarth;
    [SerializeField]
    float p_mySpeed;
    [SerializeField]
    float p_myDistance;
    [SerializeField]
    float p_myHumans;
    [SerializeField]
    GameObject p_myHumanPrefab;
    [SerializeField]
    AudioSource p_myAudioSource;

    bool p_myIsPlaying;

    BuildingScript p_myBuildingScript;

    public void setIsPlaying(bool value)
    {
        p_myIsPlaying = value;
    }

    void Start ()
    {
        p_myEarth = GameObject.FindGameObjectWithTag("Earth");
        transform.LookAt(p_myEarth.transform.position);
        p_myBuildingScript = GetComponent<BuildingScript>();
        p_myBuildingScript.enabled = false;
    }

	void Update ()
    {
        if (p_myIsPlaying)
        {
            float distance = Vector3.Distance(transform.position, p_myEarth.transform.position);
            if (distance > p_myDistance)
            {
                transform.position = Vector3.Lerp(transform.position, p_myEarth.transform.position, p_mySpeed * Time.deltaTime);
            }
            else
            {
                for (int i = 0; i < p_myHumans; i++)
                {
                    GameObject newhuman = PoolManager.Instantiation(p_myHumanPrefab.tag, transform.position, Quaternion.identity);
                    newhuman.transform.parent = p_myEarth.transform;
                }
                transform.parent = p_myEarth.transform;
                if (!p_myAudioSource.isPlaying)
                {
                    p_myAudioSource.Play();
                }
                if (HumanManager.getInfinity())
                {
                    p_myBuildingScript.enabled = true;
                }
                Destroy(this);
            }
        }
	}
}
