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

public class SimpleCrystalScript : MonoBehaviour {

    Collider collider;

    Renderer rend;

    Color OGColor;

    public Vector3 LaunchDirection = Vector3.right;

    AudioSource AudioS;
    AudioClip aclip;

    private void Start()
    {
        aclip = Resources.Load("crystal") as AudioClip;
        AudioS = gameObject.AddComponent<AudioSource>();
        AudioS.spatialBlend = 0.5f;
        AudioS.loop = false;
        AudioS.playOnAwake = false;
        AudioS.clip = aclip;

        collider = GetComponent<Collider>();
        rend = GetComponent<Renderer>();
        OGColor = rend.material.GetColor("_EmissionColor");

    }

    private void OnTriggerEnter(Collider col)
    {
        if(col.tag == "particle")
        {
            print("hit");
            ParticleController pc = col.gameObject.GetComponent<ParticleController>();
            pc.Direction = LaunchDirection ;
            
        }
    }

    private void Update()
    {
        rend.material.SetColor("_EmissionColor", rend.material.GetColor("_EmissionColor") * 0.9f + OGColor * 0.1f);
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.collider.tag == "Particle")
        {
            

            print("hit2");
            Debug.DrawLine(col.transform.position, col.transform.position + (LaunchDirection + transform.right) * 5f, Color.green, 5f);
            Physics.IgnoreCollision(col.collider, collider);

            ParticleController pc = col.gameObject.GetComponent<ParticleController>();
            rend.material.SetColor("_EmissionColor", rend.material.GetColor("_EmissionColor") * 0.9f + pc.LightColor * 0.5f);
            Debug.DrawLine(col.transform.position, col.transform.position + (LaunchDirection + transform.right) * 5f, Color.green, 5f);
            if (Vector3.Angle(LaunchDirection + transform.right, pc.Direction) < 90)
            {
                pc.Direction = LaunchDirection ;
            }
            else
            {
                pc.Direction = -(LaunchDirection );
            }

            StartCoroutine( ResetCollide(col.collider, collider));

            AudioS.Stop();
            AudioS.Play();
        }


       
    }
    IEnumerator ResetCollide(Collider col1, Collider col2)
    {
        yield return new WaitForSeconds(0.4f);
        Physics.IgnoreCollision(col1, col2, false);
    }
}



       