using MySqlX.XDevAPI;
using System.Text.Json;

namespace Aberwyn.Data
{
    public class DelugeClient
    {
        private readonly HttpClient _http;
        private readonly string _url;
        private string _sessionId;

        public DelugeClient(HttpClient httpClient, string baseUrl = "http://192.168.1.3:8112/json")
        {
            _http = httpClient;
            _url = baseUrl;
        }

        public async Task<bool> LoginAsync(string password)
        {
            var payload = new
            {
                method = "auth.login",
                @params = new object[] { password },
                id = 1
            };

            var response = await _http.PostAsJsonAsync(_url, payload);
            var json = await response.Content.ReadFromJsonAsync<JsonElement>();

            // spara sessioncookie för framtida requests
            if (response.Headers.TryGetValues("Set-Cookie", out var cookies))
            {
                _sessionId = cookies.FirstOrDefault()?.Split(';')[0];
                if (!_http.DefaultRequestHeaders.Contains("Cookie"))
                    _http.DefaultRequestHeaders.Add("Cookie", _sessionId);
            }

            return json.GetProperty("result").GetBoolean();
        }

        public async Task<bool> AddMagnetAsync(string magnetLink)
        {
            var payload = new
            {
                method = "core.add_torrent_url",
                @params = new object[] { magnetLink, new { } },
                id = 2
            };

            var response = await _http.PostAsJsonAsync(_url, payload);
            var json = await response.Content.ReadFromJsonAsync<JsonElement>();
            return json.GetProperty("result").ValueKind != JsonValueKind.Null;
        }
        public async Task<bool> AddTorrentUrlAsync(string torrentUrl)
        {
            var payload = new
            {
                method = "core.add_torrent_url",
                @params = new object[]
                {
            torrentUrl,
            new
            {
                download_location = "/download/incomplete",
                move_completed = true,
                move_completed_path = "/media/Movies",
            }
                },
                id = 3
            };

            var response = await _http.PostAsJsonAsync(_url, payload);
            var json = await response.Content.ReadFromJsonAsync<JsonElement>();

            return json.GetProperty("result").ValueKind != JsonValueKind.Null;
        }

    }
}
