using System;
using Cirno.Scripts;
using Cirno.Scripts.Utils;
using Godot;
using Godot.Collections;

namespace Cirno._3D.TrenchBroom.EntityScripts.Solid;

[Tool]
public partial class FuncShroud : StaticBody3D, IActivable
{
    [Export] public string TargetName { get; private set; }
    [Export] public bool OneTime { get; private set; }

    private bool _enabled = true;
    private bool _activable = true;

    public void _func_godot_apply_properties(Dictionary<string, Variant> props)
    {
        TargetName = props["targetname"].AsString();
        OneTime = props["one_time"].AsBool();
    }
    
    public override void _Ready()
    {
        if (Engine.IsEditorHint())
        {
            HideShroud();
            return;
        };

        if (!string.IsNullOrWhiteSpace(TargetName))
        {
            this.AddToGroup(TargetName);
        }

        if (_enabled)
        {
            ShowShroud();
        }
        else
        {
            HideShroud();
        }
    }

    public bool Activate(ActivationType activationType = ActivationType.Toggle)
    {
        if (!_activable) return false;
        switch (activationType)
        {
            case ActivationType.Toggle:
            case ActivationType.Use:
                Toggle();
                break;
            case ActivationType.Enable:
            case ActivationType.Close:
                ShowShroud();
                break;
            case ActivationType.Disable:
            case ActivationType.Open:
                HideShroud();
                break;

            case ActivationType.Destroy:
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(activationType), activationType, null);
        }

        if (OneTime)
        {
            _activable = false;
        }
        
        return true;
    }

    public void Toggle()
    {
        if (!_activable) return;
        if (_enabled)
        {
            HideShroud();
        }
        else
        {
            ShowShroud();
        }
    }

    private void HideShroud()
    {
        if (!_activable) return;
        _enabled = false;
        this.Hide();
    }

    private void ShowShroud()
    {
        if (!_activable) return;
        _enabled = true;
        this.Show();
    }
}