using Godot;

namespace Newlon.Components.GUI.Seedpackets;

public partial class Seedpacket : TextureButton
{
    public static AudioStream TapStream = ResourceLoader.Load<AudioStream>("res://assets/audio/gui/tap.mp3");
    public static AudioStream UntapStream = ResourceLoader.Load<AudioStream>("res://assets/audio/gui/tap2.mp3");
    public static AudioStream LiftStream = ResourceLoader.Load<AudioStream>("res://assets/audio/gui/seedlift.mp3");
    private const string PATH_TO_PACKED_SCENE = "res://scenes/gui/seedpacket.tscn";
    private DisplayResource _resource;
    private Label _cost;
    private TextureRect _icon;
    private Timer _timer;
    private SeedpacketHandler _handler;

    public bool disablePacket = false;

    public static PackedScene Prefab { get; private set; }

    // Node overrides
    public override void _Ready()
    {
        if (_resource != null)
                UpdateContents();
        if (Prefab == null)
        {
            Prefab = ResourceLoader.Load<PackedScene>(PATH_TO_PACKED_SCENE);
        }
        _cost = GetNode<Label>("Cost");
        _icon = GetNode<TextureRect>("PlantPreviewContainer/Preview");
        _timer = GetNode<Timer>("RechargeTimer");
    }
    public override void _Process(double delta)
    {
        Disabled = disablePacket || _timer.TimeLeft > 0;
        if (Disabled)
        {
            FocusMode = FocusModeEnum.None;
        }
        else
        {
            FocusMode = FocusModeEnum.All;
        }
        if (_handler is ISeedpacketProcess processHandler) processHandler.Process();
    }
    public void SetResource(DisplayResource resource )
    {
        _resource = resource;
        
        UpdateContents();
    }

    public DisplayResource GetResource()
    {
        return _resource;
    }

    public void SetHandler(SeedpacketHandler newHandler)
    {
        disablePacket = false;
        _handler = newHandler;
    }

    protected virtual void UpdateContents()
    {
        _cost.Text = _resource.Cost.ToString();
        _icon.Texture = _resource.Preview;
        _timer.WaitTime = _resource.ReloadTime;
        if (_resource.customFrame != null)
        {
            TextureNormal = _resource.customFrame.frame;
            _cost.LabelSettings = _resource.customFrame.font;
        }
    }

    public override void _Pressed()
    {
        GrabFocus();
        if (_handler is ISeedpacketPress pressHandler)
            pressHandler.Pressed();
    }

    public void Recharge()
    {
        _timer.Start();
        ReleaseFocus();
    }

    public void OnUnfocused()
    {
        if (_handler is ISeedpacketUnfocus unfocusHandler) unfocusHandler.OnUnfocused();
    }
}
