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

public class BombTrigger : MonoBehaviour {

    [Header("Required Object Refs.")]
    [Space]

    GameManager _gameManager;
    PlayerController _playerController;
    Rigidbody2D _rigidbody2D;

    [Space]
    [Header("Bomb Launch Force")]
    [Space]

    public float bombForce;

    [Space]
    [Header("Bomb Life Span")]
    [Space]

    public float bombLife;

    [Space]
    [Header("Bomb Damage")]
    [Space]

    [SerializeField]
    private int bombDamage = 3;

    private void OnEnable() {

        _gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
        _gameManager.BombLaunch();

        Invoke("SetInactive" , bombLife);

        _playerController = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();

        _rigidbody2D = gameObject.GetComponent<Rigidbody2D>(); 

        if(_playerController.isFacingRight) {
            _rigidbody2D.AddForce(Vector2.right * bombForce , ForceMode2D.Impulse);

        } else {
            _rigidbody2D.AddForce(Vector2.left * bombForce , ForceMode2D.Impulse);
        }
    }

    private void OnDisable() {
        CancelInvoke();
    }

    private void SetInactive() {
        gameObject.SetActive(false);
    }

    private void OnTriggerEnter2D(Collider2D other) {

        if(other.tag == "Enemy") {
            _gameManager.BombDetonation();

            EnemyHealth enemyHealth = other.GetComponent<EnemyHealth>();

            enemyHealth.TakeDamage(bombDamage);
            SetInactive();
        }
    }
}
