using Cirno.Scripts.Activables;
using Cirno.Scripts.Resources;
using Godot;

namespace Cirno.Scripts.Actors;

[Tool]
public partial class TeleporterMarker : FeatureMarker
{
    private Texture2D _markerTexture;
    private Teleporter _spawnedTeleporter;
    public Teleporter SpawnedTeleporter => _spawnedTeleporter;

    [Export]
    public TeleporterMarkerType Type { get; set; }
    
    [Export]
    public Texture2D MarkerTexture
    {
        get => _markerTexture;
        set
        {
            _markerTexture = value;
            if (Engine.IsEditorHint())
            {
                QueueRedraw();
            }
        }
    }
    
    public override void _Draw()
    {
        if (!Engine.IsEditorHint()) return;
        if (MarkerTexture is null) return;

        DrawTexture(MarkerTexture, -new Vector2(MarkerTexture.GetWidth() / 2f, MarkerTexture.GetHeight() / 2f));
    }

    public TeleporterMarker Spawn(RogueliteMapTheme mapTheme)
    {
        if (Engine.IsEditorHint()) return null;
        if (_spawnedTeleporter is not null) return this;
        
        _spawnedTeleporter = this.CreateSibling<Teleporter>(Type is TeleporterMarkerType.NextLevel ? mapTheme.LevelTeleporterPrefab : mapTheme.TeleporterPrefab);

        if (Type is TeleporterMarkerType.Receiver or TeleporterMarkerType.Start or TeleporterMarkerType.NextLevel)
        {
            _spawnedTeleporter.IsEnabled = false;
        }
        else
        {
            _spawnedTeleporter.IsEnabled = true;
        }

        if (Type is TeleporterMarkerType.InvisibleReceiver or TeleporterMarkerType.NextLevel)
        {
            _spawnedTeleporter.Invisible = true;
        }

        if (Type is TeleporterMarkerType.NextLevel && _spawnedTeleporter is LevelTeleporter levelTeleporter)
        {
            levelTeleporter.LevelPath = mapTheme.LevelTeleporterDestinationPath;
            levelTeleporter.SaveInventory = true;
        }
        
        return this;
    }
}

public enum TeleporterMarkerType
{
    Receiver,
    InvisibleReceiver,
    Start,
    BranchReturn,
    Boss,
    NextLevel
}