using DoomDeathmatch.Script;
using DoomDeathmatch.Script.Model.Weapon;
using Engine.Graphics.Texture;
using Engine.Scene.Component.BuiltIn.Renderer;
using Engine.Util;

namespace DoomDeathmatch.Component.MVC.Weapon;

public class WeaponView : Engine.Scene.Component.Component
{
  private readonly TextRenderer _weaponName;
  private readonly TextRenderer _weaponAmmo;
  private readonly Box2DRenderer _weaponSprite;

  private AnimationPlayer<Texture>? _weaponFireAnimation;
  private Texture? _idleTexture;

  public WeaponView(TextRenderer parWeaponName, TextRenderer parWeaponAmmo, Box2DRenderer parWeaponSprite)
  {
    _weaponName = parWeaponName;
    _weaponAmmo = parWeaponAmmo;
    _weaponSprite = parWeaponSprite;
  }

  public override void Update(double parDeltaTime)
  {
    _weaponFireAnimation?.Update(parDeltaTime);
  }

  public void UpdateView(WeaponData parWeaponData)
  {
    UpdateAmmoView(parWeaponData);
    _weaponName.Text = $"Оружие: {parWeaponData.Name}";

    _idleTexture = EngineUtil.AssetResourceManager.Load<Texture>(parWeaponData.IdleTexture);
    _weaponSprite.Texture = _idleTexture;

    _weaponFireAnimation?.Reset();
    if (_weaponFireAnimation != null)
    {
      _weaponFireAnimation.OnFrameChanged -= OnAnimationFrame;
      _weaponFireAnimation.OnFinish -= OnAnimationFinish;
    }

    var frames = parWeaponData.FireAnimation.Select(EngineUtil.AssetResourceManager.Load<Texture>).ToList();

    _weaponFireAnimation = new AnimationPlayer<Texture>(parWeaponData.FireAnimationDuration) { Frames = frames };
    _weaponFireAnimation.OnFrameChanged += OnAnimationFrame;
    _weaponFireAnimation.OnFinish += OnAnimationFinish;
  }

  public void UpdateAmmoView(WeaponData parWeaponData)
  {
    _weaponAmmo.Text = $"Патроны: {parWeaponData.Ammo}/{parWeaponData.MaxAmmo}";
  }

  public void Fire()
  {
    _weaponFireAnimation?.Start();
  }

  private void OnAnimationFrame(Texture parFrameTexture)
  {
    _weaponSprite.Texture = parFrameTexture;
  }

  private void OnAnimationFinish()
  {
    _weaponSprite.Texture = _idleTexture;
  }
}