using Lada.Framework.Data.Domains.Cms;
using Lada.Framework.Data.Enums;
using Lada.Framework.Data.Repositories;
using Lada.Framework.Infrastructures.Helpers;
using Microsoft.EntityFrameworkCore;
using System.Globalization;
using System.Xml.Linq;

namespace ladaexpress.vn.Infrastructures.Services
{
    public interface IUrlRecordService
    {
        /// <summary>
        /// Tạo lead
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        Task<string> GenerateSiteMapXml();

        /// <summary>
        /// Sinh nội dung robots
        /// </summary>
        /// <returns></returns>
        Task<string> GenerateRobots();
    }


    public class UrlRecordService : IUrlRecordService
    {
        private readonly IRepository<UrlRecord> _urlRecordRepository;
        public UrlRecordService(IRepository<UrlRecord> urlRecordRepository)
        {
            _urlRecordRepository = urlRecordRepository;
        }
        public async Task<string> GenerateRobots()
        {
            var rs = string.Empty;
            rs = "User-agent: *";
            rs += "\n" + "Disallow:";
            rs += "\n\n" + "Sitemap: https://ladaexpress.vn/sitemap.xml";
            return rs;
        }


        public async Task<string> GenerateSiteMapXml()
        {
            var urlRecords = new List<UrlRecord>();
            var homeRecord = new UrlRecord()
            {
                Slug = "",
                Frequency = SitemapFrequency.Monthly,
                UpdatedTime = DateTime.Now.StartOfDay().AddHours(5).AddDays(-20),
                Priority = 0.6
            };
            urlRecords.Add(homeRecord);
            var introRecord = new UrlRecord()
            {
                Slug = "gioi-thieu",
                Frequency = SitemapFrequency.Monthly,
                UpdatedTime = DateTime.Now.StartOfDay().AddHours(5).AddDays(-20),
                Priority = 0.6
            };
            urlRecords.Add(introRecord);
            var serviceRecord = new UrlRecord()
            {
                Slug = "dich-vu",
                Frequency = SitemapFrequency.Monthly,
                UpdatedTime = DateTime.Now.StartOfDay().AddHours(5).AddDays(-20),
                Priority = 0.6
            };
            urlRecords.Add(serviceRecord);
            var newsRecord = new UrlRecord()
            {
                Slug = "tin-tuc",
                Frequency = SitemapFrequency.Daily,
                UpdatedTime = DateTime.Now.StartOfDay().AddHours(5).AddDays(-1),
                Priority = 0.8
            };

            urlRecords.Add(newsRecord);

            var careerRecord = new UrlRecord()
            {
                Slug = "tuyen-dung",
                Frequency = SitemapFrequency.Daily,
                UpdatedTime = DateTime.Now.StartOfDay().AddHours(5).AddDays(-1),
                Priority = 0.8
            };
            urlRecords.Add(careerRecord);

            var contactRecord = new UrlRecord()
            {
                Slug = "lien-he",
                Frequency = SitemapFrequency.Monthly,
                UpdatedTime = DateTime.Now.StartOfDay().AddHours(5).AddDays(-20),
                Priority = 0.6
            };
            urlRecords.Add(contactRecord);


            var dynamicUrlRecords = await _urlRecordRepository.Query()
                .Where(s => s.IncludeInSiteMap && s.TagId == null).OrderBy(s => s.Id).ToListAsync();
            if (dynamicUrlRecords != null && dynamicUrlRecords.Any())
            {
                urlRecords.AddRange(dynamicUrlRecords);
            }


            var siteMapDoc = GenerateSiteMap(urlRecords);

            return siteMapDoc.ToString();

        }




        XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
        XNamespace xmlnsXhtml = "http://www.w3.org/1999/xhtml";
        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
        public XDocument GenerateSiteMap(IEnumerable<UrlRecord> items)
        {


            var sitemap = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement(xmlns + "urlset",
                          new XAttribute("xmlns", xmlns),
                          new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                          new XAttribute(XNamespace.Xmlns + "xhtml", xmlnsXhtml),
                          new XAttribute(xsi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),
                          from item in items
                          select CreateItemElement(item)
                          )
                     );

            return sitemap;
        }
        public XElement CreateItemElement(UrlRecord item)
        {
            var loc = $"https://ladaexpress.vn/{item.Slug.ToLowerInvariant()}";
            var itemElement = new XElement(xmlns + "url", new XElement(xmlns + "loc", loc));

            // all other elements are optional

            if (item.UpdatedTime.HasValue)
                itemElement.Add(new XElement(xmlns + "lastmod", item.UpdatedTime.Value.ToString("yyyy-MM-dd")));


            itemElement.Add(new XElement(xmlns + "changefreq", item.Frequency.ToString().ToLower()));


            itemElement.Add(new XElement(xmlns + "priority", item.Priority.ToString("F1", CultureInfo.InvariantCulture)));

            return itemElement;
        }
    }
}
