using Cirno.Scripts.Components.Actors;
using Godot;

public partial class EnemyPossessionMovement : ActorFreeMovement 
{

    private ActorAi _actorAi;
    // State accessor

    private AiState _previousAiState;

    [Export]
    public AnimatedSprite2D PossessionSprite { get; private set; }

    [Export] public StringName ControlEndAction { get; private set; } = "pause";

    [Export] public StringName ShootAction { get; private set; } = "shoot";
    
    [Export] public DamageReceiverActorModule DamageReceiver { get; private set; }
    
    [Export] public Weapon EquippedWeapon;
    
    public override void Init(Actor parent)
    {
        base.Init(parent);

        _actorAi = parent.GetNode<ActorAi>("ActorAi");
        _parent.OnControlAssumed += AssumeControl;

        _previousAiState = _actorAi.Ai;

        parent.OnDeath += () =>
        {
            if (_actorAi.Ai is AiState.Controlled)
            {
                ResumeControl();
            }
        };
    }

    public override void Update(double deltaTime)
    {
        if (_actorAi.Ai is not AiState.Controlled) return;
        
        if (GetActionPressed(ShootAction))
        {
            Shoot();
        }
        
        if (GetActionJustPressed(ControlEndAction))
        {
            if (GameManager.Instance.ToggleControlMode() is GameState.Playing)
            {
                ResumeControl();
            }
        }
    }
    
    private void Shoot()
    {
        if (EquippedWeapon == null) return;
        
        var direction = FacingDirection.Normalized();
        
        EquippedWeapon.ShootDirection = direction;
        
        EquippedWeapon.Shoot(BulletOwner.Player);
    }

    public override void PhysicsUpdate(double delta)
    {
        if (IsDestroyed) return;
        if (_actorAi.Ai is AiState.Controlled) 
            base.PhysicsUpdate(delta);
    }

    public void AssumeControl()
    {
        GameManager.Instance.CameraTargetObject(_parent);
        //GameManager.Instance.Player.RequestMovementDisable(true);
        GameManager.Instance.Player.SetState(PlayerState.Controlling);

        _previousAiState = _actorAi.Ai;
        _actorAi.Ai = AiState.Controlled;

        DamageReceiver.BulletGroup = BulletOwner.Player;
        
        PossessionSprite?.Show();
    }

    public void ResumeControl() 
    {
        _actorAi.Ai = _previousAiState;

        GameManager.Instance.CameraTargetPlayer();
        //GameManager.Instance.Player.RequestMovementDisable(false);
        GameManager.Instance.Player.SetState(PlayerState.Active);
        
        DamageReceiver.BulletGroup = BulletOwner.Enemy;
        
        PossessionSprite?.Hide();
    }

}