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

public class MinionThrower : MonoBehaviour {

    public Entity[] minionPrefabs;
    public GameObject aimArrow;

    bool isInThrowMode;
    Vector2 throwDirection = Vector2.right;
    MinionBar minionBar;
    VampireEntity vampireEntity;
    float currentCooldownTimer;
    float currentInitialCooldown;

    void Awake() {
        vampireEntity = GetComponent<VampireEntity>();
        minionBar = FindObjectOfType<MinionBar>();
        aimArrow.SetActive(false);
    }

    void Start() {
        foreach (Entity minion in minionPrefabs) {
            minionBar.AddMinionType(minion);
        }
    }

    void FixedUpdate() {
        if(currentCooldownTimer > 0f) {
            currentCooldownTimer -= Time.fixedDeltaTime;
            minionBar.UpdateReload(currentCooldownTimer / currentInitialCooldown);
        }
    }

    public void ToggleThrowMode(InputAction.CallbackContext context) {
        if (context.performed) {
            isInThrowMode = true;
            aimArrow.SetActive(true);
        } else if (context.canceled) {
            PerformThrow();
            isInThrowMode = false;
            aimArrow.SetActive(false);
        }
    }

    public void AimThrow(InputAction.CallbackContext context) {
        throwDirection = context.ReadValue<Vector2>().normalized;
        aimArrow.transform.rotation = Quaternion.FromToRotation(transform.right, throwDirection);
    }

    void PerformThrow() {
        if (!isInThrowMode || currentCooldownTimer > 0f) {
            return;
        }

        float minionHealthCost = 10f; // TODO
        if(minionHealthCost >= vampireEntity.Health) {
            return;
        }
        vampireEntity.TakeDamage(minionHealthCost);

        currentInitialCooldown = 2f; // TODO
        currentCooldownTimer = currentInitialCooldown;
        minionBar.UpdateReload(currentCooldownTimer / currentInitialCooldown);

        Entity newMinion = Instantiate(minionBar.GetCurrentMinion().gameObject, transform.position + new Vector3(throwDirection.x, throwDirection.y, 0f) * 1f, Quaternion.identity).GetComponent<Entity>();
        newMinion.gameFlowManager = vampireEntity.gameFlowManager;
        // Apply throw force
    }

}
