using Netina.Common.Extensions;
using Netina.Domain.Dtos.RequestDtos.SeedDtos;
using Netina.Domain.Entities.Blogs;
using Netina.WordPressDBConverter.Models;
using Newtonsoft.Json;
using Netina.Common.Models.Api;
using Netina.Domain.Dtos.SmallDtos;
using Netina.Domain.Enums;
using Netina.WordPressDBConverter.Services.RestServices;
using Refit;
using System.Reflection.Metadata;
using HtmlAgilityPack;
using System.Net.Http;
using System.Text.RegularExpressions;


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


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");

List<SeedBlogCategoryRequestDto> categories = new List<SeedBlogCategoryRequestDto>();

List<WordPressPostTagDto> tags = new List<WordPressPostTagDto>();
foreach (var taxonomy in termTaxonomies)
{
    if (taxonomy.taxonomy == "category")
    {
        var term = terms.FirstOrDefault(t => t.term_id == taxonomy.term_id);
        if (term != null)
            categories.Add(new SeedBlogCategoryRequestDto
            {
                BaseCategoryId = term.term_id.ToInt(),
                Description = taxonomy.description,
                Slug = term.slug,
                Name = term.name
            });
    }

    if (taxonomy.taxonomy == "post_tag")
    {
        var term = terms.FirstOrDefault(t => t.term_id == taxonomy.term_id);
        if (term != null)
            tags.Add(new WordPressPostTagDto
            {
                TermId = term.term_id.ToInt(),
                Tag = term.name
            });
    }

}
var categoriesRest = new Dictionary<int, Guid>();
//categoriesRest = await RestWrapper.Instance.SeedRestApi.SeedBlogCategoriesAsync(categories, "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");
Console.WriteLine($"{categories.Count} BlogCategory Added  Success !");


//CREATE BLOG PART
List<SeedBlogRequestDto> blogs = new List<SeedBlogRequestDto>();
var random = new Random(1532);
int postedCounter = 0;
int postCounter = 0;
int uploadedCounter = 0;
var wpPosts = posts.Where(p => p.post_type is "page" or "post").Skip(336).ToList();
foreach (var wordPressPostDto in wpPosts)
{
    try
    {
        SeedBlogRequestDto blog;
        Guid categoryId = default;
        string postTags = string.Empty;
        var postTermRelations = termRelationships.Where(p => p.object_id == wordPressPostDto.ID).ToList();
        foreach (var postTermRelation in postTermRelations)
        {
            var taxanomy = termTaxonomies.FirstOrDefault(f => f.term_taxonomy_id == postTermRelation.term_taxonomy_id);
            if (taxanomy != null)
            {
                if (taxanomy.taxonomy == "category")
                    categoryId = categoriesRest.FirstOrDefault(c => c.Key == taxanomy.term_id.ToInt()).Value;
                if (taxanomy.taxonomy == "post_tag")
                    postTags += tags.FirstOrDefault(t => t.TermId == taxanomy.term_id.ToInt())?.Tag + " , ";
            }
        }

        if (categoryId == default)
            categoryId = categoriesRest.FirstOrDefault(c => c.Key == 0).Value;
        var files = new List<StorageFileSDto>();
        string pattern = "<img\\s+[^>]*>";

        // Use Regex to match the pattern in the HTML content
        MatchCollection matches = Regex.Matches(wordPressPostDto.post_content, pattern);
        if (matches.Count > 0)
        {
            foreach (Match match in matches)
            {
                try
                {
                    Console.WriteLine(match.Value);

                    // Extract 'src' attribute value from the <img> tag (using another regex)
                    string srcPattern = "src\\s*=\\s*\"([^\"]+)\"";
                    Match srcMatch = Regex.Match(match.Value, srcPattern);

                    if (srcMatch.Success)
                    {
                        string oldSrc = srcMatch.Groups[1].Value;
                        using var httpClient = new HttpClient();
                        var imageBytes = await httpClient.GetByteArrayAsync(oldSrc);
                        var uploadFile = new FileUploadRequest
                        {
                            ContentType = "image/jpeg",
                            FileName = $"{StringExtensions.GetId(10)}.jpg",
                            FileUploadType = FileUploadType.Image,
                            StringBaseFile = Convert.ToBase64String(imageBytes),
                        };
                        var fileRest = await RestWrapper.Instance.UploadRestApi.UploadAsync(uploadFile);
                        string newSrc = $"https://storage.hamyanedalat.com/{fileRest.FileLocation}";
                        wordPressPostDto.post_content = wordPressPostDto.post_content.Replace(oldSrc, newSrc);
                        uploadedCounter++;
                        Console.WriteLine($"{uploadedCounter} File Uploaded Success !");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    continue;

                }
            }
        }

        //var thumbnailMeta = postMetas.FirstOrDefault(pm => pm.post_id == wordPressPostDto.ID && pm.meta_key == "_thumbnail_id");
        //if (thumbnailMeta != null)
        //{
        //    var thumbnail = posts.FirstOrDefault(p => p.ID.ToInt() == thumbnailMeta.meta_value.ToInt());
        //    if (thumbnail != null)
        //    {
        //        using var httpClient = new HttpClient();
        //        var imageBytes = await httpClient.GetByteArrayAsync(thumbnail.guid);
        //        var uploadFile = new FileUploadRequest
        //        {
        //            ContentType = thumbnail.post_mime_type,
        //            FileName = $"{StringExtensions.GetId(10)}.jpeg",
        //            FileUploadType = FileUploadType.Image,
        //            StringBaseFile = Convert.ToBase64String(imageBytes),
        //        };
        //        var fileRest = await RestWrapper.Instance.UploadRestApi.UploadAsync(uploadFile);

        //        files.Add(new StorageFileSDto
        //        {
        //            FileLocation = fileRest.FileLocation,
        //            FileName = fileRest.FileName,
        //            Name = fileRest.FileName,
        //            FileType = StorageFileType.Image
        //        });
        //        Console.WriteLine($"Thumbnail uploaded : {thumbCounter++}");
        //    }
        //}

        blog = new SeedBlogRequestDto
        {
            CategoryId = categoryId,
            Content = wordPressPostDto.post_content,
            IsSuggested = false,
            ReadingTime = random.Next(1, 15),
            Title = wordPressPostDto.post_title,
            Files = files,
            Slug = wordPressPostDto.post_name
        };

        blogs.Add(blog);

        await RestWrapper.Instance.SeedRestApi.SeedBlogsAsync(new List<SeedBlogRequestDto> { blog },
            "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");

        Console.WriteLine($"{postCounter++} / {wpPosts.Count()} Blog Added Success !");
    }
    catch (Exception e)
    {

        continue;
    }
}

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;
//}