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

public class Projectile : MonoBehaviour {

    public GameObject destroyEffect;

    float timer = -1f;
    float timer2 = -1;

    private Rigidbody2D myRigidbody2D;
    private Transform m_arm;

    private bool m_playerSwitch;
    private float m_projectileForce;
    private int m_forceMultiplier = 1;

    private GameObject m_player2;
    private GameObject m_player1;

    // Update is called once per frame
    void Update ()
    {
        transform.right = Vector3.Slerp(transform.right, myRigidbody2D.velocity.normalized, Time.deltaTime*10);

        //Debug.DrawRay(transform.position, -transform.right * 10, Color.red, 10);
        //Debug.DrawRay(transform.position, myRigidbody2D.velocity.normalized * 10, Color.blue, 10);

        if (timer <0.0f) // Le projectile se détruit au bout de 20 sec s'il n'a pas touché de collider
            timer = Time.time + 20.0f;

        if (timer >0f && Time.time > timer)
            DestroyProjectile();

        if(transform.position.y < -8f)
            DestroyProjectile();
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        DestroyProjectile();    
    }

    public void SetProjectileProperties(bool player, float projectileForce)
    {
        m_playerSwitch = player;
        m_projectileForce = projectileForce;
        ProjectileInitialization();
    }

    private void ProjectileInitialization()
    {
        myRigidbody2D = GetComponent<Rigidbody2D>();

        if (m_playerSwitch)
        {
            m_arm = GameObject.FindGameObjectWithTag("ArmLeft").transform;
            m_forceMultiplier = -1;
        }

        else if (!m_playerSwitch)
        {
            m_arm = GameObject.FindGameObjectWithTag("ArmRight").transform;
            m_forceMultiplier = 1;
        }

        //on récupère la valeur de la foce du projectile calculé dans le shootcontroller et on s'en sert pour mettre une force sur le projectile
        myRigidbody2D.AddForce(m_forceMultiplier * m_arm.right * m_projectileForce, ForceMode2D.Impulse);
        transform.right = myRigidbody2D.velocity.normalized;
    }

    void DestroyProjectile()
    {
        Instantiate(destroyEffect, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }
}
