using System.IO;
using Content.Client.Administration.Managers;
using Content.Client.Decals.UI;
using Content.Client.Sandbox;
using Content.Shared.Administration;
using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Prototypes;

namespace Content.Client.Administration.UI.Tabs.AdminbusTab
{
    [GenerateTypedNameReferences]
    public sealed partial class AdminbusTab : Control
    {
        public AdminbusTab()
        {
            RobustXamlLoader.Load(this);
            IoCManager.InjectDependencies(this);
            // For the SpawnEntitiesButton and SpawnTilesButton we need to do the press manually
            // TODO: This will probably need some command check at some point
            SpawnEntitiesButton.OnPressed += SpawnEntitiesButtonOnOnPressed;
            SpawnTilesButton.OnPressed += SpawnTilesButtonOnOnPressed;
            SpawnDecalsButton.OnPressed += SpawnDecalsButtonOnPressed;
            LoadGamePrototypeButton.OnPressed += LoadGamePrototypeButtonOnOnPressed;
            LoadGamePrototypeButton.Visible = IoCManager.Resolve<IClientAdminManager>().HasFlag(AdminFlags.Query);
        }

        private async void LoadGamePrototypeButtonOnOnPressed(BaseButton.ButtonEventArgs obj)
        {
            var dialogManager = IoCManager.Resolve<IFileDialogManager>();
            var loadManager = IoCManager.Resolve<IGamePrototypeLoadManager>();

            var stream = await dialogManager.OpenFile();
            if (stream is null)
                return;

            // ew oop
            var reader = new StreamReader(stream);
            var proto = await reader.ReadToEndAsync();
            loadManager.SendGamePrototype(proto);
        }

        private void SpawnEntitiesButtonOnOnPressed(BaseButton.ButtonEventArgs obj)
        {
            EntitySystem.Get<SandboxSystem>().ToggleEntitySpawnWindow();
        }

        private void SpawnTilesButtonOnOnPressed(BaseButton.ButtonEventArgs obj)
        {
            EntitySystem.Get<SandboxSystem>().ToggleTilesWindow();
        }

        private void SpawnDecalsButtonOnPressed(BaseButton.ButtonEventArgs obj)
        {
            EntitySystem.Get<SandboxSystem>().ToggleDecalsWindow();
        }
    }
}
