using UnityEngine;
using System.Collections;

public class EnemyMissile : MonoBehaviour
{
    public float launchDate;
    public AudioSource source1;
    public GameObject boom;
    public ParticleSystem traineeTorpille;
    public AudioClip torpedoBoomSFX;
    private GameObject monVaisseau;
    Vector3 newvectdir;
    bool boomed = false;
    public float dureeDeVie;
    
    


    // Use this for initialization
    void Start()
    {
        launchDate = Time.time;
        boom.SetActive(false);
        traineeTorpille.Play();
        newvectdir = monVaisseau.GetComponent<Ennemy>().vecteurDirecteur.normalized;
        if (monVaisseau.tag == "BigBoss")
        {
            dureeDeVie = 6.0f;
        }
        else
        {
            dureeDeVie = 3.0f;
        }

    }

    // Update is called once per frame
    void Update()
    {
        
        if (!boomed)
        {
            transform.Translate(newvectdir * Time.deltaTime * 200.0f);
        }


        if (Time.time - launchDate > dureeDeVie && !boomed)
        {
            //Debug.Log("boom");
            StartCoroutine("explosion");
            boomed = true;
        }



    }
    void OnTriggerEnter(Collider collision)
    {

        //Debug.Log("I touch " + collision.gameObject.name);

        Ennemy submarine = collision.gameObject.GetComponent<Ennemy>();
        Missile missile = collision.gameObject.GetComponent<Missile>();
        MoveSubmarine submarinePlayer = collision.gameObject.GetComponent<MoveSubmarine>();
        GameObject plateforme = GameObject.Find("plateforme");
        Plateform plateform = collision.gameObject.GetComponent<Plateform>();

        if (submarine == null && missile!=null || submarine == null && plateform != null)
        {
            // For all others : kill!
            StartCoroutine("explosion");
            boomed = true;


        }
        if (submarine == null && missile == null && plateform==null)
        {
            if(submarinePlayer!=null)
            {
                HealthSubmarine.touched = true;
                StartCoroutine("explosion");
                boomed = true;
            }
            else
            {
                Destroy(collision.gameObject);
                StartCoroutine("explosion");
                boomed = true;
            }
          
        }



        // Test ennemi here




    }

    public IEnumerator explosion()
    {
        traineeTorpille.Stop();
        boom.SetActive(true);
        GetComponent<Renderer>().enabled = false;
        source1.clip = torpedoBoomSFX;
        source1.Play();
        yield return new WaitForSeconds(1.0f);
        Destroy(gameObject);
      
    }

    public void SetVaisseau(GameObject v)
    {
        monVaisseau = v;
    }
}

