#if DEBUG
//#define TestBesonderenArtikel
//#define SKIP_DOWNLOAD
#endif
using ArtikelUpdateOpencart.Import.Models;
using CoreFtp;
using CoreFtp.Enum;
using CsvHelper;
using CsvHelper.Configuration;
using Renci.SshNet;
using Serilog;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WK5.Core;
using WK5.Core.Email;

namespace ArtikelUpdateOpencart.Import
{
    public class LieferantenImportBluestar : LieferantenImportBase<BluestarArtikel>
    {

        public const int LIEFERANTENNUMMER = 70038;
        public List<BluestarStock> StockDaten { get; set; } = new();
        public List<BluestarKarley> KarleyDaten { get; set; } = new();

        public LieferantenImportBluestar(string downloadUrl, ILogger logger) : base(LIEFERANTENNUMMER, downloadUrl, logger)
        {

        }
        public override async Task DownloadAsync()
        {
            string filenameKarley = Path.Combine(GlobalConfig.W4TmpFolderSrv01, "BlueStar_Karley.txt");
            string filenameItems = Path.Combine(GlobalConfig.W4TmpFolderSrv01, "BlueStar_Items.txt");
            string filenameStock = Path.Combine(GlobalConfig.W4TmpFolderSrv01, "BlueStar_Stock.txt");

#if !SKIP_DOWNLOAD
            for (int i = 0; i < 20; i++)
            {
                StreamReader? downloadReader = null;
                StreamWriter? myFile = null;
                try
                {
                    using FtpClient ftpClient = new FtpClient(new FtpClientConfiguration
                    {
                        Host = "bsnavision.cadinor.com",
                        Username = "BSGE-46552",
                        Password = "KarDeG581!",
                        Port = 21,
                        EncryptionType = FtpEncryption.Implicit,
                        IgnoreCertificateErrors = true
                    });

                    await ftpClient.LoginAsync();
                    var tempFile = new FileInfo(filenameKarley);
                    using (var ftpReadStream = await ftpClient.OpenFileReadStreamAsync("BlueStar_Karley.txt"))
                    {
                        
                        using var fileWriteStream = tempFile.OpenWrite();
                        await ftpReadStream.CopyToAsync(fileWriteStream);
                    }

                    

                    tempFile = new FileInfo(filenameItems);
                    using (var ftpReadStream = await ftpClient.OpenFileReadStreamAsync("Generic Files/BlueStar_Items.txt"))
                    {
                        using var fileWriteStream = tempFile.OpenWrite();
                        await ftpReadStream.CopyToAsync(fileWriteStream);
                    }

                    tempFile = new FileInfo(filenameStock);
                    using (var ftpReadStream = await ftpClient.OpenFileReadStreamAsync("Generic Files/BlueStar_Stock.txt"))
                    {
                        using var fileWriteStream = tempFile.OpenWrite();
                        await ftpReadStream.CopyToAsync(fileWriteStream);
                    }


                    await ftpClient.LogOutAsync();
                    i = 20;
                }
                catch (Exception ex)
                {
                    if (i == 19)
                    {
                        await EmailController.FehlerMailSendenAsync("Bluestar Download Fehler", "Fehler beim runterladen der Datei, Lieferantenupdate wurde abgebrochen.");
                        Environment.Exit(0);
                    }
                    else
                    {
                        await Task.Delay(60000); // 1 Minute Warten
                    }
                }
                finally
                {
                    downloadReader?.Close();
                    myFile?.Close();
                }
            }
#endif
            // Items
            using (TextReader reader = new StreamReader(filenameItems))
            {
                CsvConfiguration configuration = new CsvConfiguration(new CultureInfo("de-DE"));
                configuration.BadDataFound = null;
                configuration.TrimOptions = TrimOptions.Trim;
                configuration.Delimiter = ";";
                configuration.HasHeaderRecord = false;
                configuration.Encoding = Encoding.UTF8;

                ArtikeldatenLieferant = new List<BluestarArtikel>();
                using var csv = new CsvReader(reader, configuration);
                while (csv.Read())
                {
                    try
                    {
                        var artikel = csv.GetRecord<BluestarArtikel>();
                        ArtikeldatenLieferant.Add(artikel);
                    }
                    catch (Exception ex)
                    {
                        Log.Logger.Error("Fehler bei Konvertierung in BluestarArtikel: {error}", ex);
                    }

                }
            }

            using (TextReader reader = new StreamReader(filenameStock))
            {
                CsvConfiguration configuration = new CsvConfiguration(new CultureInfo("de-DE"));
                configuration.BadDataFound = null;
                configuration.TrimOptions = TrimOptions.Trim;
                configuration.Delimiter = ";";
                configuration.HasHeaderRecord = false;
                configuration.Encoding = Encoding.UTF8;

              
                using var csv = new CsvReader(reader, configuration);
                while (csv.Read())
                {
                    try
                    {
                        var stock = csv.GetRecord<BluestarStock>();
                        StockDaten.Add(stock);
                    }
                    catch (Exception ex)
                    {
                        Log.Logger.Error("Fehler bei Konvertierung in BluestarStock: {error}", ex);
                    }

                }
            }

            using (TextReader reader = new StreamReader(filenameKarley))
            {
                CsvConfiguration configuration = new CsvConfiguration(new CultureInfo("de-DE"));
                configuration.BadDataFound = null;
                configuration.TrimOptions = TrimOptions.Trim;
                configuration.Delimiter = ";";
                configuration.HasHeaderRecord = false;
                configuration.Encoding = Encoding.UTF8;


                using var csv = new CsvReader(reader, configuration);
                while (csv.Read())
                {
                    try
                    {
                        var data = csv.GetRecord<BluestarKarley>();
                        KarleyDaten.Add(data);
                    }
                    catch (Exception ex)
                    {
                        Log.Logger.Error("Fehler bei Konvertierung in BluestarKarley: {error}", ex);
                    }

                }
            }
        }

        public override async Task RunAsync()
        {
            using FbController2 fbController = new FbController2();
            List<string> vorhanden_hersteller = await GetVorhandeneHerstellerAsync(fbController).ToListAsync();
            HerstellerErsetzen ersetzen = await HerstellerErsetzen.CreateAsync();
            int zähler = 0;
            foreach (var artikel in ArtikeldatenLieferant)
            {
#if TestBesonderenArtikel
                if (!artikel.SKU.Equals("XXX", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
#endif
                ++zähler;
                Console.Write("\r{0}/{1}\t", zähler, ArtikeldatenLieferant.Count);

                //Überprüft ob der Hersteller in der W4 existiert
                if (!vorhanden_hersteller.Contains(ersetzen.GetHerstellerErsetzt(artikel.ManufacturerName)))
                {
                    continue;
                }

                // Überprüft ob der Artikel in IgnoreLieferantenArtikel.txt steht
                if (ersetzen.IsArtikelIgnored(artikel.SKU, LIEFERANTENNUMMER))
                {
                    continue;
                }

                // Nicht jeder Artikel in deren Liste ist bei uns drin
                BluestarKarley? karleyArtikel = KarleyDaten.FirstOrDefault(x => x.SKU == artikel.SKU);

                if (karleyArtikel is not null)
                {
                    decimal ek = karleyArtikel.NetPrice;
                    ek = ersetzen.GibStueckzahlVPEPreis(ek, LIEFERANTENNUMMER, artikel.SKU);

                    decimal lagerbestand = StockDaten.FirstOrDefault(x => x.SKU == artikel.SKU)?.QtyAvailable ?? 0;

                    int mindestmenge = ersetzen.GibMindestmenge(LIEFERANTENNUMMER, artikel.SKU);


                    GlobalLieferantenArtikel lieferantenArtikel = new GlobalLieferantenArtikel()
                    {
                        LieferantenId = LIEFERANTENNUMMER,
                        Bestellnummer = artikel.SKU,
                        NettoEinkaufspreis = ek,
                        Hersteller = artikel.ManufacturerName,
                        Herstellernummer = artikel.SKU,
                        Kurzbezeichnung = artikel.LongDescription,
                        Lagerbestand = lagerbestand,
                        EAN = string.Empty,
                        Versandkosten = 5.95m,
                        Mindestbestellmenge = mindestmenge
                    };

                    await LieferantenUpdateGlobalAsync(lieferantenArtikel, ersetzen, fbController, _logger);
                }
            }

            await DeleteInaktiveLieferantenartikelAsync(LIEFERANTENNUMMER, fbController);
        }
    }
}
