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

public class Bullet : MonoBehaviour
{
    public static float Scale = 0.3f;
    private bool isAlive = false;
    private Vector3 direction;
    public float speed = 10f;
    private int playerLayer;
    private int bubbleLayer;
    public int damage = 1;

    private bool touchWall = false;

    public void Init(Vector3 dir)
    {
        transform.localScale = Vector3.one * Scale;
        direction = dir;
        playerLayer = LayerMask.NameToLayer("Player");
        bubbleLayer = LayerMask.NameToLayer("Bubble");
        isAlive = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (!isAlive) return;
        transform.position += direction * Time.deltaTime * speed;
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.layer == playerLayer)
        {
            Player1 p1 = collision.gameObject.GetComponent<Player1>();
            Player2 p2 = collision.gameObject.GetComponent<Player2>();
            if(p1 != null)
            {
                p1.TakeDamage(damage, direction);
            }
            else if(p2 != null)
            {
                p2.TakeDamage(damage, direction);
            }
            collision.gameObject.GetComponent<Player>().TakeDamage(damage, direction);
            Destroy(gameObject);
        }
        else if (collision.gameObject.layer == bubbleLayer)
        {
            Debug.Log("Touch Bubble");
            Destroy(collision.gameObject);
            Destroy(gameObject);
        }

        if (touchWall) return;
        touchWall = true;
        StartCoroutine(DelayWall());
        if (collision.gameObject.layer == LayerMask.NameToLayer("WallY"))
        {
            direction.x = -direction.x;
            Debug.Log("Touch Y  ");
        }
        else if (collision.gameObject.layer == LayerMask.NameToLayer("WallX"))
        {
            direction.z = -direction.z;
            Debug.Log("Touch X");
        }
    }

    IEnumerator DelayWall()
    {
        yield return new WaitForSeconds(0.05f);
        touchWall = false;
    }

}
