using System;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Actuators;

[RequireComponent(typeof(MovementController))]
public class NPC : Agent
{
    public Team Team { get; set; }

    [HideInInspector]
    private float LastTimeHit;
    public CharacterCondition Condition;

    public MovementController moveController;
     
    private void Start()
    {
        Condition = new CharacterCondition();
        moveController = gameObject.GetComponent<MovementController>();
    }

    public override void OnEpisodeBegin()
    {

    }

    public override void CollectObservations(VectorSensor sensor)
    {
        sensor.AddObservation(Condition.HealthPoints);
        sensor.AddObservation(Condition.ArmourPoints);
        sensor.AddObservation(Condition.Ammunition);
        sensor.AddObservation((int)Condition.npcState);
    }

    public override void Heuristic(in ActionBuffers actionsOut)
    {
        var discreteActionsOut = actionsOut.DiscreteActions;
        if (Input.GetKeyDown(KeyCode.W))
        {
            discreteActionsOut[0] = 1;
        }
    }

    public override void OnActionReceived(ActionBuffers actions)
    {
        if (actions.DiscreteActions[0] == 1)
            moveController.MoveToRandomPoint();
    }

    public event Action<object> OnKilledEvent;
    public void GetDamage(float damage)
    {
        Condition.GiveHealth(-Mathf.RoundToInt(damage * (1 - Condition.ArmourPoints * 0.5f)));
        Condition.GiveArmour(-Mathf.RoundToInt(Mathf.Sqrt(damage) * 5));

        if (Condition.HealthPoints < 0)
            OnKilledEvent?.Invoke(this);
    }
}
