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

public class OnHitExplode : MonoBehaviour
{
    public List<GameObject> DestructableParts = new List<GameObject>();
    public GameObject NonDestructablePart;

    public GameObject KraterPrefab;

    private bool destroyObject = false;
    public float DestroyAfter = 3;

    private ScoreCounter scoreCounter;

    private AudioSource audioSource;
    public AudioClip[] shoot;
    private AudioClip shootClip;

    public void Start()
    {
        scoreCounter = GameObject.FindObjectOfType<ScoreCounter>();
        audioSource = gameObject.GetComponent<AudioSource>();
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "Shield")
        {
            GameObject.Destroy(this.gameObject.GetComponent<EffectSpawner>().EffectInstance);
            GameObject.Destroy(this.gameObject);

            other.GetComponentInParent<SatControl>().Activate(false);
            scoreCounter.UpdateScore(1);
        }
    }



    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "GravitySource")
        {
            var rotComp = this.GetComponent<RandomRotate>();
            rotComp.enabled = false;

            NonDestructablePart.SetActive(false);

            foreach (var obj in DestructableParts)
            {
                obj.SetActive(true);
            }

            GameObject.Destroy(this.gameObject.GetComponent<EffectSpawner>().EffectInstance);
            destroyObject = true;
            scoreCounter.UpdateScore(-1);

            int index = Random.Range(0, shoot.Length);
            shootClip = shoot[index];
            audioSource.clip = shootClip;
            audioSource.Play();

            var contact = collision.GetContact(0);

            var rotated = Quaternion.Euler(90, 90, 0) * contact.normal;

            GameObject.Instantiate(KraterPrefab, contact.point, Quaternion.LookRotation(-1 * contact.normal, Vector3.Cross(rotated, contact.normal)));
        }
    }

    public void Update()
    {
        if (destroyObject)
        {
            DestroyAfter -= Time.deltaTime;

            if (DestroyAfter <= 0)
            {
                GameObject.Destroy(this.gameObject);
            }
        }
    }
}
