using Serilog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace ecoDMS.Library
{
    /// <summary>
    /// EcoDMS gibt uns die ganzen Int32 als String zurck. Also der Converter. Optional kann man noch auf JSON.Net (Newtonsoft) umsteigen.
    /// </summary>
    public class Int32Converter : System.Text.Json.Serialization.JsonConverter<int>
    {
        public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                string stringValue = reader.GetString() ?? String.Empty;
                if (int.TryParse(stringValue, out int value))
                {
                    return value;
                }
            }
            else if (reader.TokenType == JsonTokenType.Number)
            {
                return reader.GetInt32();
            }

            throw new System.Text.Json.JsonException();
        }

        public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
        {
            writer.WriteNumberValue(value);
        }
    }

    public class EcoDmsController : IDisposable
    {
        public HttpClient Client { get; }
        public Uri BasisUrl { get; }
        public string AnmeldeDaten { get; }
        public ILogger Logger { get; }

        public List<EcoDMSStatiCL>? EcoDmsStatusListe { get; protected set; }

        public List<EcoDMSdocInfoCL>? EcoDmsdocInfoCLs { get; protected set; }
        public List<EcoSearchFilter> EcoSearchFilters { get; protected set; } = new List<EcoSearchFilter>();


        // In CreateAsync gesetzt
#nullable disable
        public List<EcoDMSDokumentenartenCL> EcoDmsDokumentenArtenListe { get; protected set; }
        public Dokumentenarten Dokumentenarten { get; protected set; }
        public Klassifizierungsattribute ClassifyAttributes { get; protected set; }
        public List<EcoDMSOrdnerCL> EcoDmsOrdnerListe { get; protected set; }
#nullable enable
        protected EcoDmsController(Uri basisUrl, string anmeldeDaten, ILogger logger, int timeout = 100)
        {
            BasisUrl = basisUrl;
            AnmeldeDaten = anmeldeDaten;
            Logger = logger;
            Client = new HttpClient
            {
                BaseAddress = BasisUrl,
                Timeout = TimeSpan.FromSeconds(timeout)
            };
            Client.DefaultRequestHeaders.Accept.Clear();
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Base64Encode(anmeldeDaten));
            Client.DefaultRequestHeaders.Add("Set-Cookie", "token=test; path=/");
        }



        public static Task<EcoDmsController> CreateAsync(Uri basisUrl, string anmeldeDaten, ILogger logger, int timeout = 100)
        {
            EcoDmsController controller = new EcoDmsController(basisUrl, anmeldeDaten, logger, timeout);
            return controller.InitializeAsync();

        }

        protected async Task<EcoDmsController> InitializeAsync()
        {
            ClassifyAttributes = new Klassifizierungsattribute(await GetClassifyAttributesAsync());
            EcoDmsOrdnerListe = await GetFoldersAsync();
            EcoDmsDokumentenArtenListe = await GetDocumentTypesAsync();
            Dokumentenarten = new Dokumentenarten(EcoDmsDokumentenArtenListe);
            EcoDmsStatusListe = await GetStatiAsync();
            return this;
        }


        /// <summary>
        /// Encodiert einen normalen String in einen Base64 String
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        private static string Base64Encode(string plainText)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(plainTextBytes);
        }

        public void Dispose()
        {
            Client.Dispose();
            GC.SuppressFinalize(this);
        }

        #region EcoDMS Funktionen
        public async Task<bool> AnmeldenAsync()
        {
            //Verbinden:
            bool angemeldet = false;
            try
            {

                var msg = await Client.GetStringAsync("connect/1");
                //Erfolgreich = Login for user ecodms successful, selected Archive 1.
                if (msg.Contains("successful") && msg.Contains("selected Archive"))
                {
                    angemeldet = true;
                }
                Debug.WriteLine(msg);
                //Testen ob Verbindung okay (gemäß Doku unbedingt nachschießen
                msg = await Client.GetStringAsync("test");
                if (msg != "<h1>API TEST: OK</h1>")
                {
                    angemeldet = false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }
            return angemeldet;
        }
        public async Task<bool> AbmeldenAsync()
        {
            bool abgemeldet = false;
            try
            {
                var msg = await Client.GetStringAsync("disconnect");
                // Logoff for user ecodms successfull <<< wenn erfolgreich
                if (msg.Contains("successfull") && msg.Contains("Logoff"))
                {
                    abgemeldet = true;
                }
                Debug.Write(msg);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }
            return abgemeldet;
        }

        /// API: 6 Aufruf der ecoDMS-Attribute

        public async Task<EcoDMSApiStatistics?> GetApiStatistics()
        {
            try
            {
                HttpResponseMessage result = await Client.GetAsync($"apiStatistics");
                if (result.IsSuccessStatusCode)
                {
                    var response = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var serializeOptions = new JsonSerializerOptions();

                    serializeOptions.Converters.Add(new Int32Converter());
                    EcoDMSApiStatistics? stats = JsonSerializer.Deserialize<EcoDMSApiStatistics>(response, serializeOptions);
                    return stats;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return null;
            }
        }

        public async Task<bool> APIConnectsVerfügbar()
        {
            EcoDMSApiStatistics? stat = await GetApiStatistics();

            if (stat == null)
            {
                return false;
            }

            return stat.DownloadCount + stat.UploadCount < stat.MaxCount;
        }

        public async Task<int> VerbleibendeAPIConnects()
        {
            EcoDMSApiStatistics? stat = await GetApiStatistics();

            if (stat == null)
            {
                return 0;
            }

            return stat.MaxCount - (stat.DownloadCount + stat.UploadCount);
        }

        public async Task<List<string>> GetRolesAsync()
        {
            List<string>? ecoRoles = new List<string>();

            try
            {
                var StreamTask = Client.GetStreamAsync("roles");
                ecoRoles = await JsonSerializer.DeserializeAsync<List<string>>(await StreamTask);
                if (ecoRoles is null)
                {
                    throw new ArgumentNullException(nameof(ecoRoles));
                }
#if DEBUG
                foreach (var rolle in ecoRoles)
                {
                    Console.WriteLine(rolle);
                }
#endif
                return ecoRoles;
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                Logger.Error(ex.Message);
            }

            return ecoRoles ?? new List<string>();
        }
        public async Task<List<EcoDMSStatiCL>> GetStatiAsync()
        {
            List<EcoDMSStatiCL>? ecoStati = null;
            try
            {
                var StreamTask = Client.GetStreamAsync("status");
                ecoStati = await JsonSerializer.DeserializeAsync<List<EcoDMSStatiCL>>(await StreamTask);
                if (ecoStati is null)
                {
                    throw new ArgumentNullException(nameof(ecoStati));
                }
#if DEBUG
                foreach (var ecoStatus in ecoStati)
                {
                    Console.WriteLine(ecoStatus.Name + ":" + ecoStatus.Id);

                }
#endif
                return ecoStati;
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                Logger.Error(ex.Message);
            }
            return new List<EcoDMSStatiCL>();
        }

        // 6.2.1 Liste aller Rollen
        public async Task<List<EcoDMSRollenCL>> GetRolesAsync(bool NurUserRollen)
        {
            List<EcoDMSRollenCL>? rollen = null;
            try
            {
                string URL = NurUserRollen ? "userRoles" : "roles";
                rollen = await JsonSerializer.DeserializeAsync<List<EcoDMSRollenCL>>(await Client.GetStreamAsync(URL));
                if (rollen is null)
                {
                    throw new ArgumentNullException(nameof(rollen));
                }
#if DEBUG
                foreach (var ecoRolle in rollen)
                {
                    Console.WriteLine(ecoRolle.Name);

                }
#endif
                return rollen;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }
            return new List<EcoDMSRollenCL>();
        }

        // 6.3 Dokumentenarten
        public async Task<List<EcoDMSDokumentenartenCL>> GetDokumentenArtenAsync()
        {
            List<EcoDMSDokumentenartenCL>? ecoDokumentenarten = null;
            try
            {
                var streamTask = Client.GetStreamAsync("types");
                ecoDokumentenarten = await JsonSerializer.DeserializeAsync<List<EcoDMSDokumentenartenCL>>(await streamTask);
                if (ecoDokumentenarten is null)
                {
                    throw new ArgumentNullException(nameof(ecoDokumentenarten));
                }
                Dokumentenarten = new Dokumentenarten(ecoDokumentenarten);
#if DEBUG
                foreach (var Dokumentenart in ecoDokumentenarten)
                {
                    Console.WriteLine(Dokumentenart.Name + ":" + Dokumentenart.Id);
                }
#endif
                return ecoDokumentenarten;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }
            return new List<EcoDMSDokumentenartenCL>();
        }

        //6.4 Liefert eine Liste aller Ordner, die in der Ordnerstruktur von ecoDMS angelegt sind
        public async Task<List<EcoDMSOrdnerCL>> GetOrdnerAsync()
        {
            List<EcoDMSOrdnerCL>? ecoOrdner = null;
            try
            {
                var StreamTask = Client.GetStreamAsync("folders");
                ecoOrdner = await JsonSerializer.DeserializeAsync<List<EcoDMSOrdnerCL>>(await StreamTask);
                if (ecoOrdner is null)
                {
                    throw new ArgumentNullException(nameof(ecoOrdner));
                }
#if DEBUG
                foreach (var ordner in ecoOrdner)
                {
                    Console.WriteLine(ordner.OId + ":" + ordner.Foldername);
                }
#endif

                return ecoOrdner;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }

            return new List<EcoDMSOrdnerCL>();
        }

        public async Task LoadClassifyAttributesAsync()
        {
            try
            {
                string message = await Client.GetStringAsync("classifyAttributes");
                Dictionary<string, string>? classifyAttributes = JsonSerializer.Deserialize<Dictionary<string, string>>(message);
                if (classifyAttributes is null)
                {
                    throw new ArgumentNullException(nameof(classifyAttributes));
                }
                ClassifyAttributes = new Klassifizierungsattribute(classifyAttributes);
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }
        }

        public async Task<string> GetDokumentAsync(string zielpfad, int docId, int docVersion = 0)
        {
            //Token macht sinn, wenn man z.B. nach 10 Sekunden ohne Antwort abbrechen will
            CancellationTokenSource source = new CancellationTokenSource();
            source.CancelAfter(10000);
            CancellationToken token = source.Token;

            Client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/pdf"));
            string parameter = $"document/{docId}";
            if (docVersion > 0)
            {
                parameter += "/version/" + docVersion.ToString();
            }

            var response = await Client.GetAsync(parameter, token);

            var dateiName = response.Content.Headers.GetValues("Content-Disposition").ToArray()[0].Replace("attachment; filename=", "");
            using (var fs = new FileStream(Path.Combine(zielpfad, dateiName), FileMode.Append))
            {
                await response.Content.CopyToAsync(fs);
            }

            return Path.Combine(zielpfad, dateiName);
        }

        public async Task<List<EcoDMSdocInfoCL>> EcoSucheDoksAsync(List<EcoSearchFilter> ecoSearchFilters)
        {
            //Rückgabewert: 
            List<EcoDMSdocInfoCL> suchergebnisse = new List<EcoDMSdocInfoCL>();
            //Token macht sinn, wenn man z.B. nach 10 Sekunden ohne Antwort abbrechen will
            CancellationTokenSource source = new CancellationTokenSource();
            source.CancelAfter(10000);
            CancellationToken token = source.Token;

            try
            {
                //Für die Serialisierung müssen wir unbedingt eine List übergeben, sonst funktioniert es nicht + UTF8 Kodierung
                string json = JsonSerializer.Serialize(ecoSearchFilters);
                Logger.Information("SucheDoksAsync");
                Logger.Information(json);
                HttpContent httpContent = new StringContent(JsonSerializer.Serialize(ecoSearchFilters), Encoding.UTF8, "application/json");
                HttpResponseMessage result = await Client.PostAsync("searchDocumentsExt?maxDocumentCount=1000", httpContent, token);

                if (result.IsSuccessStatusCode)
                {
                    var response = result.Content.ReadAsStringAsync().Result;
                    suchergebnisse = JsonSerializer.Deserialize<List<EcoDMSdocInfoCL>>(response) ?? new List<EcoDMSdocInfoCL>();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Logger.Error(ex.Message);
            }
            return suchergebnisse;
        }

        /// <summary>
        /// Wenn Upload Erfolgreich, dann gibt es die docID zurück
        /// </summary>
        /// <param name="pdfDatei"></param>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="EcoDmsHttpException">Kann auftreten, wenn die Klassifizierung für eine Dokument fehlerhaft ist, oder die API Connects aufgebraucht sind</exception>
        /// <returns></returns>
        public async Task<int> UploadFileAsync(string pdfDatei, Dictionary<string, string> klassifizierung, List<string> readRoles, List<string> editRoles, bool versionControlled = false)
        {
            int docId = 0;
            try
            {
                using var httpContent = new MultipartFormDataContent();
                byte[] file = File.ReadAllBytes(pdfDatei);
                var byteArrayContent = new ByteArrayContent(file);
                httpContent.Add(byteArrayContent, "file", new FileInfo(pdfDatei).Name);

                HttpResponseMessage result = await Client.PostAsync($" uploadFile/{versionControlled}", httpContent);
                if (result.IsSuccessStatusCode)
                {
                    var response = await result.Content.ReadAsStringAsync();
                    int dateiNummer = JsonSerializer.Deserialize<int>(response);

                    HttpResponseMessage res = await Client.GetAsync($"documentInfo/{dateiNummer}");
                    var docInfoObject = JsonSerializer.Deserialize<List<EcoDMSdocInfoCL>>(await res.Content.ReadAsStringAsync());
                    if (docInfoObject is not null)
                    {
                        foreach (var classify in klassifizierung)
                        {
                            if (docInfoObject[0].ClassifyAttributes.ContainsKey(classify.Key))
                            {
                                docInfoObject[0].ClassifyAttributes[classify.Key] = classify.Value;
                            }
                        }

                        docInfoObject[0].EditRoles = editRoles;
                        docInfoObject[0].ReadRoles = readRoles;

                        docId = await ClassifyAsync(docInfoObject[0]);
                    }
                }
                else
                {
                    throw new EcoDmsHttpException($"Fehler beim hochladen des Dokuments \"{pdfDatei}\" in ecoDMS.", result.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Logger.Error(ex.Message);
                throw;
            }
            return docId;
        }

        /// <summary>
        /// Lädt ein Byte Array mit einem Dateinamen an ecoDMS hoch
        /// </summary>
        /// <param name="data">Die Daten die an ecoDMS hochgeladen werden sollen</param>
        /// <param name="filename">Der Name der "Datei" die ecoDMS erwartet</param>
        /// <param name="versionControlled">Gibt an ob es sich unter ecoDMS um ein versioniertes Dokument handelt</param>
        /// <returns>Gibt einen <see cref="Task{TResult}"/> of <see cref="int"/> zurück der die DocId des hochgeladenen Dokument enthält</returns>           
        public async Task<int> UploadAsync(byte[] data, string filename, bool versionControlled = false)
        {
            if (!await APIConnectsVerfügbar())
            {
                throw new EcoDmsAPIConnectsException("Es sind keine API Connects mehr vorhanden um eine Datei hochzuladen");
            }


            try
            {
                using (var content = new MultipartFormDataContent())
                {
                    var byteArray = new ByteArrayContent(data);
                    content.Add(byteArray, "file", filename);

                    HttpResponseMessage response = await Client.PostAsync($"uploadFile/{versionControlled}", content);
                    if (response.IsSuccessStatusCode)
                    {
                        int docid = JsonSerializer.Deserialize<int>(await response.Content.ReadAsStringAsync());
                        return docid;
                    }
                    else
                    {
                        throw new EcoDmsHttpException("Fehler beim hochladen der Datei", response.StatusCode);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        /// <summary>
        /// Lädt sich das <see cref="EcoDMSdocInfoCL"/> Objekt zu einer DocId aus ecoDMS
        /// </summary>
        /// <param name="docid">Die DocId zu der sich die Information geladen werden soll</param>
        /// <returns>Gibt eine <see cref="Task{TResult}"/> of <see cref="EcoDMSdocInfoCL"/> zurück</returns>
        public async Task<EcoDMSdocInfoCL?> GetInfoAsync(int docid)
        {
            try
            {
                HttpResponseMessage response = await Client.GetAsync($"documentInfo/{docid}");
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    List<EcoDMSdocInfoCL>? docInfos = JsonSerializer.Deserialize<List<EcoDMSdocInfoCL>>(json);
                    if (docInfos is null)
                    {
                        return null;
                    }

                    if (docInfos.Count > 0)
                    {
                        return docInfos[0];
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim abfragen der Dokumenten Informationen", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        private bool IsValid(EcoDMSdocInfoCL info)
        {
            foreach (KeyValuePair<string, string> kvp in info.ClassifyAttributes)
            {
                if (!ClassifyAttributes.ContainsKey(kvp.Key))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Klassifiziert ein Dokument in ecoDMS mit den gegebenen Werten
        /// </summary>
        /// <param name="info">Die Daten die in dem Dokument hinterlegt werden sollen</param>
        /// <returns>Gibt einen <see cref="Task{T}"/> of <see cref="int"/> zurück</returns>
        public async Task<int> ClassifyAsync(EcoDMSdocInfoCL info)
        {
            if (!IsValid(info))
            {
                throw new EcoDmsInvalidObject("Die Klassifizierungsinformationen sind invalide");
            }

            try
            {
#if DEBUG
                string? tmp = JsonSerializer.Serialize(info);
#endif
                HttpContent content = new StringContent(JsonSerializer.Serialize(info), Encoding.UTF8, "application/json");
                HttpResponseMessage response = await Client.PostAsync("classifyDocument", content);

                if (response.IsSuccessStatusCode)
                {
                    return JsonSerializer.Deserialize<int>(await response.Content.ReadAsStringAsync());
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim klassifizieren des Dokument", response.StatusCode);
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        /// <summary>
        /// Lädt sich aus ecoDMS eine Liste aller Ordner
        /// </summary>
        /// <returns>Gibt einen <see cref="Task{TResult}"/> of <see cref="List{T}"/> of <see cref="EcoDMSdocInfoCL"/> zurück</returns>
        public async Task<List<EcoDMSOrdnerCL>> GetFoldersAsync()
        {
            try
            {
                HttpResponseMessage response = await Client.GetAsync($"folders");
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    List<EcoDMSOrdnerCL>? folders = JsonSerializer.Deserialize<List<EcoDMSOrdnerCL>>(json);
                    return folders ?? new List<EcoDMSOrdnerCL>();
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim abfragen der Ordner", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        /// <summary>
        /// Lädt sich aus ecoDMS alle Klassifizierungs Attribute
        /// </summary>
        /// <returns>Gibt einen <see cref="Task{TResult}"/> of <see cref="Dictionary{TKey, TValue}"/> of <see cref="string"/> zurück</returns>
        public async Task<Dictionary<string, string>> GetClassifyAttributesAsync()
        {
            try
            {
                HttpResponseMessage response = await Client.GetAsync("classifyAttributes");
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    Dictionary<string, string>? attributes = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
                    return attributes ?? new Dictionary<string, string>();
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim abfragen der Klassifizierungs Attribute", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        /// <summary>
        /// Lädt sich aus ecoDMS alle Dokumenten Typen
        /// </summary>
        /// <returns>Gibt einen <see cref="Task{TResult}"/> of <see cref="List{T}"/> of <see cref="EcoDMSDokumentenartenCL"/> zurück</returns>
        public async Task<List<EcoDMSDokumentenartenCL>> GetDocumentTypesAsync()
        {
            try
            {
                HttpResponseMessage response = await Client.GetAsync("types");
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    List<EcoDMSDokumentenartenCL>? types = JsonSerializer.Deserialize<List<EcoDMSDokumentenartenCL>>(json);
                    return types ?? new List<EcoDMSDokumentenartenCL>();
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim abfragen der Dokumententypen", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        /// <summary>
        /// Lädt sich aus ecoDMS alle Benutzer Rollen
        /// </summary>
        /// <returns>Gibt einen <see cref="Task{TResult}"/> of <see cref="List{T}"/> of <see cref="string"/> zurück</returns>
        public async Task<List<string>> GetUserRolesAsync()
        {
            try
            {
                HttpResponseMessage response = await Client.GetAsync("userRoles");
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    List<string>? roles = JsonSerializer.Deserialize<List<string>>(json);
                    return roles ?? new List<string>();
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim abfragen der User Rollen", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }

        public async Task<byte[]> GetDokumentenVorschauAsync(int docId, int page, int height = 1080)
        {
            try
            {
                HttpResponseMessage response = await Client.GetAsync($"thumbnail/{docId}/page/{page}/height/{height}");
                if (response.IsSuccessStatusCode)
                {
                    byte[] data = await response.Content.ReadAsByteArrayAsync();
                    return data;
                }
                else
                {
                    throw new EcoDmsHttpException("Fehler beim abfragen der User Rollen", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }
        #endregion
    }

}
