using NetinaShop.Common.Extensions;
using NetinaShop.Domain.CommandQueries.Commands;
using NetinaShop.Domain.Dtos.RequestDtos.SeedDtos;
using NetinaShop.Domain.Dtos.SmallDtos;
using NetinaShop.WordPressDBConverter.Models;
using NetinaShop.WordPressDBConverter.Services.RestServices;
using Newtonsoft.Json;


Console.ReadKey();

try
{
    var termReader = new StreamReader("F:\\wp_terms.json");
    var termJson = termReader.ReadToEnd();
    Console.WriteLine("Terms File Read Success !");
    var terms = JsonConvert.DeserializeObject<List<WordPressTermDto>>(termJson);
    if (terms == null)
        throw new Exception("Terms is null");

    var termTaxonomyReader = new StreamReader("F:\\wp_term_taxonomy.json");
    var termTaxonomyJson = termTaxonomyReader.ReadToEnd();
    Console.WriteLine("Term Taxonomy File Read Success !");
    var termTaxonomies = JsonConvert.DeserializeObject<List<WordPressTermTaxonomyDto>>(termTaxonomyJson);
    if (termTaxonomies == null)
        throw new Exception("Term Taxonomies is null");


    var termRelationshipsReader = new StreamReader("F:\\wp_term_relationships.json");
    var termRelationshipsJson = termRelationshipsReader.ReadToEnd();
    Console.WriteLine("Term Relationships File Read Success !");
    var termRelationships = JsonConvert.DeserializeObject<List<WordPressTermRelationDto>>(termRelationshipsJson);
    if (termRelationships == null)
        throw new Exception("Term Relationships is null");

    var postReader = new StreamReader("F:\\wp_posts.json");
    var json = postReader.ReadToEnd();
    Console.WriteLine("Post File Read Success !");
    var posts = JsonConvert.DeserializeObject<List<WordPressPostDto>>(json);
    if (posts == null)
        throw new Exception("Posts is null");


    var metaReader = new StreamReader("F:\\wp_postmeta.json");
    var metaJson = metaReader.ReadToEnd();
    Console.WriteLine("Post Metas File Read Success !");
    var postMetas = JsonConvert.DeserializeObject<List<WordPressPostMetaDto>>(metaJson);
    if (postMetas == null)
        throw new Exception("Post Metas is null");

//CREATE CATEGORY PART
    List<SeedCategoryRequestDto> categories = new List<SeedCategoryRequestDto>();
    foreach (var taxonomy in termTaxonomies)
    {
        if (taxonomy.taxonomy == "product_cat")
        {
            var term = terms.FirstOrDefault(t => t.term_id == taxonomy.term_id);
            if (term != null)
                categories.Add(new SeedCategoryRequestDto
                    { BaseCategoryId = term.term_id.ToInt(), Description = taxonomy.description, Name = term.name });
        }
    }

    var categoriesRest = await RestWrapper.Instance.SeedRestApi.SeedCategoriesAsync(categories,"kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");
    Console.WriteLine($"{categories.Count} ProductCategory Added  Success !");

    //CREATE BRAND PART
    List<SeedBrandRequestDto> brands = new List<SeedBrandRequestDto>();
    foreach (var taxonomy in termTaxonomies)
    {
        if (taxonomy.taxonomy == "pa_brand")
        {
            var term = terms.FirstOrDefault(t => t.term_id == taxonomy.term_id);
            if (term != null)
                brands.Add(new SeedBrandRequestDto{BaseBrandId = term.term_id.ToInt(),Description = taxonomy.description,Name = term.name});
        }
    }
    var brandsRest = await RestWrapper.Instance.SeedRestApi.SeedBrandsAsync(brands, "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");

    Console.WriteLine($"{brands.Count} Brand Added  Success !");
    //CREATE PRODUCT PART
    List<CreateProductCommand> products = new List<CreateProductCommand>();
    foreach (var wordPressPostDto in posts.Where(p => p.post_type == "product"))
    {
        CreateProductCommand product;
        Guid brandId = default;
        Guid categoryId = default;
        var postTermRelations = termRelationships.Where(p => p.object_id == wordPressPostDto.ID);
        foreach (var postTermRelation in postTermRelations)
        {
            var taxanomy = termTaxonomies.FirstOrDefault(f => f.term_taxonomy_id == postTermRelation.term_taxonomy_id);
            if (taxanomy != null)
            {
                if (taxanomy.taxonomy == "pa_brand")
                    brandId = brandsRest.FirstOrDefault(f => f.Key == taxanomy.term_id.ToInt()).Value;
                if (taxanomy.taxonomy == "product_cat")
                    categoryId = categoriesRest.FirstOrDefault(c => c.Key == taxanomy.term_id.ToInt()).Value;
            }
        }

        if (brandId == default)
            brandId = brandsRest.FirstOrDefault(f => f.Key == 0).Value;
        if (categoryId == default)
            categoryId = categoriesRest.FirstOrDefault(c => c.Key == 0).Value;
        var price = postMetas.FirstOrDefault(pm => pm.post_id == wordPressPostDto.ID && pm.meta_key == "_price");
        if (price != null && double.TryParse(price.meta_value, out double dPrice))
            product = new CreateProductCommand(wordPressPostDto.post_title, string.Empty, wordPressPostDto.post_content,
                wordPressPostDto.post_excerpt, string.Empty, string.Empty, true, dPrice, 0,10,
                false,10,false,brandId, categoryId,
                new DiscountSDto(),new List<SpecificationSDto>(), new List<StorageFileSDto>());
        else
            product = new CreateProductCommand(wordPressPostDto.post_title, string.Empty, wordPressPostDto.post_content,
                wordPressPostDto.post_excerpt, string.Empty, string.Empty, true, 0, 0,10,false,10,
                false,brandId,categoryId,
                new DiscountSDto(),new List<SpecificationSDto>(), new List<StorageFileSDto>());

        products.Add(product);
    }

    for (int i = 0; i < products.Count / 50 ; i++)
    {
        await RestWrapper.Instance.SeedRestApi.SeedProductsAsync(products.Skip(i * 50).Take(50).ToList(),
            "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");

        Console.WriteLine($"{i*50} / {products.Count} Product Added Success !");
    }
}
catch (Exception e)
{
    Console.WriteLine(e);
    throw;
}