using Avalonia.Controls;
using Avalonia.Interactivity;
using NP.Ava.Visuals.Behaviors;
using pavesys_iRAP.ViewModels;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net.Http.Json;
using pavesys_iRAP.DTO;
using Newtonsoft.Json;
using System.Text;

namespace pavesys_iRAP.Views
{
    public partial class MainPageView : UserControl
    {
        public MainPageView()
        {
            InitializeComponent();
        }

        //Maximiza a janela após o login
        private void UserControl_Initialized(object? sender, System.EventArgs e)
        {
            var dtx = this.DataContext as MainPageViewModel;
            if (!dtx.hasMaximized)
            {
                dtx.hasMaximized = true;
                var topLevel = TopLevel.GetTopLevel(this) as Window;
                topLevel.WindowState = WindowState.Maximized;
            }
        }

        public void ClickIrap(object sender, RoutedEventArgs args)
        {
            OpenUrl(@"https://irap.org/");
        }

        public void ClickManual(object sender, RoutedEventArgs args)
        {
            OpenUrl(@"https://irap.org/specifications/");
        }
        private void OpenUrl(string url)
        {
            try
            {
                Process.Start(url);
            }
            catch
            {
                // hack because of this: https://github.com/dotnet/corefx/issues/10361
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    url = url.Replace("&", "^&");
                    Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Process.Start("xdg-open", url);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    Process.Start("open", url);
                }
                else
                {
                    throw;
                }
            }
        }

        private async void Button_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
        {
            //using (HttpClient client = new HttpClient())
            //{
            //    try
            //    {
            //        // Set the base address if needed
            //        client.BaseAddress = new Uri("http://172.233.16.164:9090/");

            //        // Send GET request to /admin/list
            //        HttpResponseMessage response = await client.GetAsync("/api/ping");

            //        // Ensure the response indicates success
            //        response.EnsureSuccessStatusCode();

            //        // Read and output the response content
            //        string content = await response.Content.ReadAsStringAsync();
            //        Debug.WriteLine("Response content:");
            //        Debug.WriteLine(content);
            //    }

            //    catch (HttpRequestException ex)
            //    {
            //        Debug.WriteLine($"Request error: {ex.Message}");

            //    }
            //    catch (Exception ex)
            //    {
            //        Debug.WriteLine(ex.ToString());
            //    }
            //}
            string token = "";
            string baseUrl = "http://172.233.16.164:9090/";
            string endpoint = "auth/login";

            var loginData = new
            {
                username = "admin",
                password = "irapServer#24"
            };


            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);

                    // Convert the loginData object to JSON
                    string jsonContent = JsonConvert.SerializeObject(loginData);
                    StringContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                    // Send POST request
                    HttpResponseMessage response = await client.PostAsync(endpoint, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("Login successful. Response:");
                        Debug.WriteLine(responseBody);
                        var authResponse = JsonConvert.DeserializeAnonymousType(responseBody, new { token = "" });


                         token = authResponse.token;
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
            }

             baseUrl = "http://172.233.16.164:9090/";
             endpoint = "admin/list";

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                    HttpResponseMessage response = await client.GetAsync(endpoint);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("GET /admin/list successful. Response:");
                        Debug.WriteLine(responseBody);
                    }
                    else
                    {
                        Debug.WriteLine($"Error: {response.StatusCode}");
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine($"Error details: {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An exception occurred:");
                Debug.WriteLine(ex.Message);
            }
        }
    }
    
}

