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

public enum SonicType { Sense, Attack };

public class Sonic : MonoBehaviour {

    public SonicType type;

    private bool isReflect = false;
    private float timer;
    private float power;
    private Vector3 reflectPoint;
    private Vector3 forwardDirection;
    private Vector3 reflectDirection;
    private Rigidbody rb;

    private void Awake () {
        rb = this.GetComponent<Rigidbody>();
    }

    public void Launch (Vector3 direction, float power, float timer) {
        //print("Launch Sonic");
        forwardDirection = direction.normalized;
        this.power = power;
        this.timer = timer;
        this.GetComponent<Rigidbody>().AddForce(forwardDirection * power);
        isReflect = StartRaycast(forwardDirection);
        StartCoroutine(_CountDown());
    }

    public bool StartRaycast (Vector3 direction) {
        RaycastHit hit;
        Ray ray = new Ray(this.transform.position, direction);
        if (Physics.Raycast(ray, out hit)) {
            reflectPoint = hit.point;
            reflectDirection = Vector3.Reflect(direction, hit.normal);
            reflectDirection = new Vector3(reflectDirection.x, 0, reflectDirection.z);
            return true;
        }
        return false;
    }

    /*public float GetTimer () {
        return timer;
    }

    public Vector3 GetReflectPoint () {
        return reflectPoint;
    }

    public Vector3 GetForwardDirection () {
        return forwardDirection;
    }

    public Vector3 GetReflectDirection () {
        return reflectDirection;
    }*/

    public float GetPower () {
        return power;
    }

    public void DestroyObject () {
        //print("Destroy Sonic");
        Destroy(this.gameObject);
    }

    public void Reflect () {
        if (isReflect) {
            forwardDirection = reflectDirection;
            rb.velocity = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
            rb.AddForce(forwardDirection * power);
            isReflect = StartRaycast(forwardDirection);
        }
    }

    public IEnumerator SoftDestroyObject () {
        ParticleSystem[] pss = this.GetComponentsInChildren<ParticleSystem>();
        foreach(ParticleSystem ps in pss) {
            ps.Stop();
        }
        yield return new WaitForSeconds(0.6f);
        DestroyObject();
    }

    private IEnumerator _CountDown () {
        while (true) {
            timer -= Time.deltaTime;
            if (timer <= 0) {
                StartCoroutine(SoftDestroyObject());
            }
            yield return null;
        }
    }

}
