using KarleyLibrary.Erweiterungen;
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WK5.Core;

namespace ArtikelUpdateOpencart
{
    internal class KarleyExport
    {

        public static async Task RunAsync(ArtikelUpdateOpencartSettings settings, ILogger logger)
        {
            using FbController2 fbController = new FbController2();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("ARTI_A_NR\tARTI_A_BEZ1\tARTI_N_VK1\tARTI_N_VK2\tARTI_N_VK4\t");
            int zähler = 1500;
            int page = 1;
            bool hasMore = true;
            do
            {
                DataTable data = await fbController.SelectDataAsync($"SELECT FIRST {zähler} SKIP {(page - 1) * zähler} ARTI_A_NR, COALESCE(ARTI_A_BEZ1, '') AS ARTI_A_BEZ1, ARTI_N_VK1, ARTI_N_VK2, ARTI_N_VK4 FROM ARTIKEL WHERE ARTI_L_INAKTIV = 'N' ORDER BY ARTI_A_NR");

                foreach (DataRow row in data.Rows)
                {
                    ExportArtikel artikel = ObjectErweiterung.DataRowZuObjekt(new ExportArtikel(), row);
                    sb.AppendLine($"\"{artikel.ARTI_A_NR}\"\t\"{artikel.ARTI_A_BEZ1.Replace("\"", "\"\"")}\"\t{artikel.ARTI_N_VK1}\t{artikel.ARTI_N_VK2}\t{artikel.ARTI_N_VK4}\t");
                }
                hasMore = data.Rows.Count is 1500;
                page++;
            }
            while (hasMore);

            await File.WriteAllTextAsync(settings.KarleyExport.ExportPfad, sb.ToString());
        }

        private class ExportArtikel
        {
            public string ARTI_A_NR { get; set; } = string.Empty;
            public string ARTI_A_BEZ1 { get; set; } = string.Empty;
            public decimal ARTI_N_VK1 { get; set; }
            public decimal ARTI_N_VK2 { get; set; }
            public decimal ARTI_N_VK4 { get; set; }
        }
    }
}
