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

public class BulletController : MonoBehaviour
{
    public BulletData data;
    [HideInInspector] public EntityController owner;
    [HideInInspector] public EntityController.DIRECTION direction = EntityController.DIRECTION.RIGHT;
    private Rigidbody2D body;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate () {
        Vector2 speed = Vector2.zero;
        if (direction == EntityController.DIRECTION.RIGHT) speed = Vector2.right;
        if (direction == EntityController.DIRECTION.LEFT) speed = Vector2.left;

        body.velocity = speed * data.speed;
    }


    ContactPoint2D[] collisionContacts;

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

    private bool isDead = false;

    public void Death()
    {
        isDead = true;
    }

    public void LateUpdate()
    {
        if (isDead) LateDeath();
    }

    public void LateDeath()
    {
        if (data.vfx_death != null)
        {
            Instantiate(data.vfx_death, transform.position, Quaternion.identity, null);
        }

        Destroy(gameObject);
    }

    private void EvaluateCollision(Collision2D collision)
    {
        if (collisionContacts == null) collisionContacts = new ContactPoint2D[10];

        EntityController controller = collision.collider.GetComponentInParent<EntityController>();
        //BulletController bullet = collision.collider.GetComponentInParent<BulletController>();

        //if (bullet != null) return;

        //if (collision.collider.gameObject.layer == LayerMask.NameToLayer("DEATH") && controller == null)
        //{
        //    return;
        //}

        if (controller != null)
        {
            if (controller.data.deflectBullets)
            {
                direction = direction == EntityController.DIRECTION.LEFT ? EntityController.DIRECTION.RIGHT : EntityController.DIRECTION.LEFT;
                return;
            } else
            {
                controller.Death();
                Death();
                return;
            }
        }

        for (int i = 0; i < collisionContacts.Length; i++)
        {
            collisionContacts[i] = new ContactPoint2D();
        }

        if (collision.GetContacts(collisionContacts) > 0)
        {
            for (int i = 0; i < collisionContacts.Length; i++)
            {
                ContactPoint2D contact = collisionContacts[i];

                if (!contact.enabled) continue;

                TilemapCollisionManager.i.DestroyTileAt(contact.point - contact.normal * 0.05f);
            }
        }

        Death();
    }
}

