using DoomDeathmatch.Component.MVC.Model;
using DoomDeathmatch.Component.MVC.Model.Weapon;
using DoomDeathmatch.Component.MVC.View;

namespace DoomDeathmatch.Component.MVC.Controller;

public class WeaponController : Engine.Scene.Component.Component
{
  public event Action<WeaponData>? OnWeaponShot;
  public WeaponData WeaponData => _weaponModel.SelectedWeapon;

  private readonly WeaponModel _weaponModel = new();
  private WeaponView _weaponView = null!;

  public override void Awake()
  {
    _weaponView = GameObject.GetComponent<WeaponView>()!;
    _weaponView.UpdateView(_weaponModel.SelectedWeapon);

    _weaponModel.OnWeaponSelected += WeaponSelected;
    WeaponSelected(null, _weaponModel.SelectedWeapon);
  }

  public bool TryShoot()
  {
    if (_weaponModel.SelectedWeapon.Ammo <= 0)
      return false;

    // _weaponModel.SelectedWeapon.Ammo--;

    OnWeaponShot?.Invoke(_weaponModel.SelectedWeapon);

    return true;
  }

  public void Reload()
  {
    _weaponModel.SelectedWeapon.Ammo = _weaponModel.SelectedWeapon.MaxAmmo;
  }

  public void AddWeapon(WeaponData parWeaponData)
  {
    if (_weaponModel.Weapons.Contains(parWeaponData))
      return;

    _weaponModel.Weapons.Add(parWeaponData);
  }

  public void RemoveWeapon(int parIndex)
  {
    if (parIndex <= 0 || parIndex >= _weaponModel.Weapons.Count)
      return;

    var newSelectedIndex = parIndex >= _weaponModel.SelectedWeaponIndex ? _weaponModel.SelectedWeaponIndex : 0;

    _weaponModel.SelectedWeaponIndex = newSelectedIndex;
    _weaponModel.Weapons.RemoveAt(parIndex);
  }

  public void SelectWeapon(int parIndex)
  {
    if (parIndex >= _weaponModel.Weapons.Count)
      return;

    _weaponModel.SelectedWeaponIndex = parIndex;
  }

  private void WeaponSelected(WeaponData? parOldWeapon, WeaponData parNewWeapon)
  {
    if (parOldWeapon != null)
      parOldWeapon.OnAmmoChanged -= _weaponView.UpdateAmmoView;

    parNewWeapon.OnAmmoChanged += _weaponView.UpdateAmmoView;
    _weaponView.UpdateView(parNewWeapon);
  }
}