using Launcher.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;

namespace Launcher
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void LogoutButton_Click(object sender, RoutedEventArgs e)
        {
            UserModel.HasLoggedOut = true;
            this.Hide();

            var loginWindow = new LoginView();
            loginWindow.ShowDialog();

            if (!loginWindow.IsSuccessfulLogin)
            {
                System.Windows.Application.Current.Shutdown();
            }
        }

        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string folderPath = System.IO.Path.Combine(folderBrowserDialog.SelectedPath, "zabgamewow3.3.5");
                Directory.CreateDirectory(folderPath);

                await DownloadHttpFiles("https://wow.zabgame.ru/wp-content/plugins/wp_lapi/files_data.json", folderPath);
            }
        }

        private async Task DownloadHttpFiles(string jsonUrl, string localPath)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(jsonUrl);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    FileData fileData = JsonConvert.DeserializeObject<FileData>(json);

                    long totalSize = fileData.TotalSize; // Получаем общий размер всех файлов

                    long downloadedSize = 0; // Инициализируем счетчик загруженного размера

                    foreach (var file in fileData.Files)
                    {
                        string directoryPath = Path.Combine(localPath, GetDirectoryPathFromUrl(file.Path));

                        if (!Directory.Exists(directoryPath))
                        {
                            Directory.CreateDirectory(directoryPath);
                        }

                        string filePath = Path.Combine(directoryPath, Path.GetFileName(file.Path));

                        using (HttpResponseMessage fileResponse = await client.GetAsync(file.Path))
                        using (HttpContent content = fileResponse.Content)
                        {
                            byte[] fileBytes = await content.ReadAsByteArrayAsync();
                            await Task.Run(() => File.WriteAllBytes(filePath, fileBytes));

                            downloadedSize += fileBytes.Length; // Увеличиваем счетчик загруженного размера

                            // Обновляем значение прогресс-бара
                            DownloadProgress.Value = (double)downloadedSize / totalSize * 100;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Failed to retrieve file data.");
                }
            }
        }

        private string GetDirectoryPathFromUrl(string url)
        {
            Uri uri = new Uri(url);
            string[] segments = uri.Segments;

            if (segments.Length > 2)
            {
                string subDirectory = string.Join("\\", segments, 1, segments.Length - 2); // -2, чтобы пропустить последний сегмент (имя файла) и "/" перед ним
                return subDirectory;
            }

            return string.Empty;
        }

    }

    public class FileData
    {
        public int Indicator { get; set; }
        public long TotalSize { get; set; }
        public List<FileItem> Files { get; set; }
    }

    public class FileItem
    {
        public string Name { get; set; }
        public long Size { get; set; }
        public string Hash { get; set; }
        public string Path { get; set; }
    }
}
