using Biskilog_Cloud.Shared.CustomModels;
using Biskilog_Cloud.Shared.Interfaces;
using Biskilog_Cloud.Shared.Models;
using System.Net.Http.Headers;
namespace ServerManager.SyncMethods
{
    public class ProductSync
    {
        private readonly IProduct m_productService;
        private HttpClient m_httpClient;
        public ProductSync(IProduct a_produtService)
        {
            m_productService = a_produtService;
            m_httpClient = new HttpClient();
        }
        /// 
        /// Returns a collection of tasks to perform a sync in the SalesInterface
        /// 
        /// 
        public IEnumerable GetProductSyncTask(HttpClient httpClient)
        {
            m_httpClient = httpClient;
            return new Task[] {
                SyncProductsAsync(),
                SyncInventoryAsync(),
                SyncInventoryEntriesAsync(),
                SyncRestockAsync(),
                SyncPriceChangesAsync(),
                SyncProductAltUnitAsync(),
                SyncStockAsync(),
                SyncBrandsAsync(),
                SyncCategoriesAsync(),
                SyncUnitOfMeasureAsync(),
            };
        }
        private async Task SyncProductsAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblproduct");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchProducts(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblproduct", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblproducts", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncInventoryAsync()
        {
          var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblInventory");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchInventory(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblInventory", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblInventory", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncInventoryEntriesAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblInventoryentries");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchInventoryEntries(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblInventoryentries", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblInventoryentry", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncRestockAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/restocklevels");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchRestockAsync(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "restocklevels", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblRestock", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncPriceChangesAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblpricechanges");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchPriceChanges(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblpricechanges", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tlpricechanges", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncProductAltUnitAsync()
        {
            try
            {
                var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/productaltunit");
                if (!responseMessage.IsSuccessStatusCode)
                {
                    return;
                }
                DateTime date = await responseMessage.Content.ReadFromJsonAsync();
                IEnumerable modifiedCart = await m_productService.FetchProductAltUnit(date, "BRID0");
                SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "productaltunit", Timestamp = DateTime.Now.AddSeconds(-10) };
                int batchSize = 200;
                int totalItems = modifiedCart.Count();
                int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
                for (int batchIndex = 0; batchIndex < batches; batchIndex++)
                {
                    List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                    var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblProductAltUnit", batch);
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                    }
                }
                //Set last sync date
                await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
            }catch (Exception ex)
            {
            }
        }
        private async Task SyncStockAsync()
        {var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tbstock");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchStockAsync(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tbstock", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblStock", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncBrandsAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblbrands");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchBrandsAsync(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblbrands", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblbrands", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncCategoriesAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/tblcategory");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchCategoriesAsync(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "tblcategory", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblCategories", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
        private async Task SyncUnitOfMeasureAsync()
        {
            var responseMessage = await m_httpClient.GetAsync("/api/SyncProducts/lastsyncdate/unitofmeasure");
            if (!responseMessage.IsSuccessStatusCode)
            {
                return;
            }
            DateTime date = await responseMessage.Content.ReadFromJsonAsync();
            IEnumerable modifiedCart = await m_productService.FetchUnitOfMeasureAsync(date, "BRID0");
            SyncTimestamp syncTimestamp = new SyncTimestamp { TableName = "unitofmeasure", Timestamp = DateTime.Now.AddSeconds(-10) };
            int batchSize = 200;
            int totalItems = modifiedCart.Count();
            int batches = (totalItems + batchSize - 1) / batchSize; // Calculate total batches
            for (int batchIndex = 0; batchIndex < batches; batchIndex++)
            {
                List batch = modifiedCart.Skip(batchIndex * batchSize).Take(batchSize).ToList();
                var response = await m_httpClient.PostAsJsonAsync("/api/SyncProducts/publish/tblunitofmeasure", batch);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"{syncTimestamp.TableName}  : Sent batch {batchIndex + 1}, Count: {batch.Count}");
                }
            }
            //Set last sync date
            await m_httpClient.PostAsJsonAsync("/api/SyncProducts/setsyncdate", syncTimestamp);
        }
    }
}