using System.Collections.ObjectModel;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.DependencyInjection;
using DynamicData;
using DynamicData.Binding;
using HetznerCloudApi;
using PSCHelpdesk.Plugins.HetznerServer.Models;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.Setting;
using ReactiveUI;

namespace PSCHelpdesk.Plugins.HetznerServer.Service;

public class ServerService: IServerService
{
    public SourceCache<Server, long> SourceCache = new (x => x.Id);
    private SettingsManager _settingsManager;
    private readonly DispatcherTimer _reloadTimer = new DispatcherTimer();
    private string _searchText = string.Empty;
    public ServerService()
    {
        _settingsManager = (SettingsManager)Ioc.Default.GetService<ISettingsManager>();

        this._reloadTimer.Tick += (sender, args) =>
        {
            this.reloadServer();
        };
        _reloadTimer.Interval = TimeSpan.FromMinutes(10);
        _reloadTimer.Start();
        
        
        Task.Run(async () => await this.reloadServer());
    }
    
    private async Task reloadServer()
    {
        var settings = new Settings();
        _settingsManager.LoadPluginSettings("HetznerSettings", settings);
        if (settings.HetznerApiKey != "")
        {
            HetznerCloudClient hetznerCloudClient = new HetznerCloudClient(settings.HetznerApiKey);

            List<HetznerCloudApi.Object.Server.Server> list = await hetznerCloudClient.Server.Get();
            foreach (var server in list)
            {
                var uiDispatcher = Ioc.Default.GetService<IUserInterfaceDispatchService>();
                await uiDispatcher.InvokeAsync(() =>
                {
                    Console.WriteLine($"Server: {server.Name}");
                    SourceCache.AddOrUpdate(new Server(server.Id, server.Name, server.ServerType.Name, server.Status,
                        server.PublicNet.Ipv4.Ip, server.PublicNet.Ipv6.Ip));
                });
                
            }
        }
    }
}