using System.Net.Http.Headers;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.DependencyInjection;
using Newtonsoft.Json.Linq;
using PSCHelpdesk.Plugins.Nextcloud.Models;
using PSCHelpdesk.Plugins.Nextcloud.ViewModels;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.Setting;

namespace PSCHelpdesk.Plugins.Nextcloud.Views;

public partial class NextcloudSettingsView : UserControl
{
    private SettingsManager settingsManager;
    private Settings settings;
    private static readonly HttpClient httpClient = new HttpClient();

    public NextcloudSettingsView()
    {
        InitializeComponent();
        settingsManager = (SettingsManager)Ioc.Default.GetService<ISettingsManager>();
        settings = new Settings();
        settingsManager.LoadPluginSettings("NextcloudSettings", settings);
    }

    private void SaveSettings_OnClick(object? sender, RoutedEventArgs e)
    {
        settings.ServerUrl = ((NextcloudSettingsViewModel)this.DataContext).ServerUrl;
        settings.Username = ((NextcloudSettingsViewModel)this.DataContext).Username;
        settings.AppPassword = ((NextcloudSettingsViewModel)this.DataContext).AppPassword;
        settingsManager.SavePluginSettings("NextcloudSettings", settings);
    }

    private async void Button_OnClick(object? sender, RoutedEventArgs e)
    {
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/ld+json"));
        httpClient.DefaultRequestHeaders.Add("User-Agent", "PSC Client");

        var stringTask = httpClient.PostAsync(settings.ServerUrl + "/index.php/login/v2", new MultipartContent());
        
        var msg = await stringTask;
        JObject response = JObject.Parse(msg.Content.ReadAsStringAsync().Result);
        Uri? uri = new Uri(response["login"].ToString());
        if (uri is not null)
        {
            Dispatcher.UIThread.Post(async () =>
            {
                bool success = await TopLevel.GetTopLevel(this)!.Launcher.LaunchUriAsync(uri);
            });
        }

        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/ld+json"));
        httpClient.DefaultRequestHeaders.Add("User-Agent", "PSC Client");
        
        while (true)
        {
            
            var pollLink = httpClient.PostAsync(
                response["poll"]["endpoint"].ToString(), 
                new FormUrlEncodedContent(new []{new KeyValuePair<string, string>("token", response["poll"]["token"].ToString())}));

            var resultPoll = await pollLink;
            if (resultPoll.IsSuccessStatusCode)
            {
                JObject responsePoll = JObject.Parse(resultPoll.Content.ReadAsStringAsync().Result);
                settings.Username = responsePoll["loginName"].ToString();
                settings.AppPassword = responsePoll["appPassword"].ToString();
                ((NextcloudSettingsViewModel)this.DataContext).Username = settings.Username;
                ((NextcloudSettingsViewModel)this.DataContext).AppPassword = settings.AppPassword;
                break;
            }
            
            Thread.Sleep(1000);
        }
        
    }
}