using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HetznerCloudApi;
using PSCHelpdesk.Plugins.HetznerServer.Models;
using PSCHelpdesk.Plugins.HetznerServer.Views;
using PSCHelpdesk.Shared.ViewModels;

namespace PSCHelpdesk.Plugins.HetznerServer.ViewModels;

public partial class ServerViewModel : ViewModelBase
{
    public ServerViewModel()
    {
        Server = new ObservableCollection<Server>();
        SelectedServer = new Server(1,"","","","","");
        loadServers();
        
    }
    
    private bool _isPagePaneOpen = false;
    public bool IsPagePaneOpen
    {
        get => _isPagePaneOpen;
        set => SetAndRaisePropertyChanged(ref _isPagePaneOpen, value);
    }
    
    private Server _selectedServer;
    public Server SelectedServer
    {
        get => _selectedServer;
        set => SetAndRaisePropertyChanged(ref _selectedServer, value);
    }
    
    private ObservableCollection<Server> _server;
    public ObservableCollection<Server> Server
    {
        get => _server;
        set => SetAndRaisePropertyChanged(ref _server, value);
    }

    private async void loadServers()
    {
        HetznerCloudClient hetznerCloudClient = new HetznerCloudClient("kcsTOjNw7YxiOGVaIrk33gIYIHmLRov9Ap6BgWxQZVJyzSsmeNpClMhpJZUYCL0k");
        
        List<HetznerCloudApi.Object.Server.Server> list = await hetznerCloudClient.Server.Get();
        foreach (var server in list)
        {
            Server.Add(new Server(server.Id, server.Name, server.ServerType.Name, server.Status, server.PublicNet.Ipv4.Ip, server.PublicNet.Ipv6.Ip));
        }
        
        SelectedServer = Server[0];
    }
    
    [RelayCommand]
    public void ShowServerDetails(Server server)
    {
        
    }
    
    [RelayCommand]
    public void OpenSCP(Server server)
    {
        
    }
    
    [RelayCommand]
    public void OpenSSH(Server server)
    {
        /*LocalSetting setting = JsonSettings.Load<LocalSetting>();
        Process.Start(string.Format(setting.SSHClientExecutable, server.Ipv4));*/
    }
    
    [RelayCommand]
    public void SelectionChanged(SelectionChangedEventArgs args)
    {
        this.SelectedServer = (args.Source as DataGrid).SelectedItem as Server;
        IsPagePaneOpen = true;
    }
    
    public UserControl GetViewControl()
    {
        return new ServerView();
    }
}