﻿using AnnuaireCertifies.Domaine;
using AnnuaireCertifies.Infrastructure.Services.Caching;
using AnnuaireCertifies.Infrastructure.Services.Depots;
using AnnuaireCertifies.WebServices.Web.Models.ModelBuilders;
using Castle.Core.Logging;
using AnnuaireCertifies.WebServices.Web.Models.Models.Nouveaute;
using System.Collections.Generic;
using System.Linq;

namespace AAnnuaireCertifies.WebServices.Web.Models.ModelBuilders
{
    public class NouveauteModelBuilder : ModelBuilderBase, INouveauteModelBuilder
    {
        public NouveauteModelBuilder(ILogger logger, IDepotFactory depotFactory, ICaching cachingService)
            : base(logger, depotFactory, cachingService)
        { }

        public NouveauteResultModel BuildNouveauteResultatModel(long langueID)
        {
            NouveauteResultModel res = new NouveauteResultModel();

            var mieuxNote = _depotFactory.ArticleDepot.GetProduitsMieuxNotes(true);
            res.MieuxNotes = AutoMapper.Mapper.Map<IEnumerable<ArticleListeResult>, IEnumerable<ArticleModel>>(mieuxNote);

            var derniersAvis = _depotFactory.ArticleAvisDepot.GetDerniersAvis(true);
            res.DerniersAvis = AutoMapper.Mapper.Map<IEnumerable<AvisResult>, IEnumerable<AvisModel>>(derniersAvis);


            var route = _depotFactory.RouteDepot.Find(x => x.LangueID == langueID && x.Code == "NOTICE_DETAILS").FirstOrDefault();

            if (route != null)
            {
                //Mieux notes
                foreach (var note in res.MieuxNotes)
                {
                    var index = note.CleArticle.LastIndexOf("-");
                    string numeroCertificat = string.Empty;
                    if (index >= 0)
                    {
                        numeroCertificat = note.CleArticle.Substring(0, index);
                    }
                    note.UrlArticle = route.Url.Replace("{reference}", numeroCertificat).Replace("{numeroCertificat}-{articleID}", note.CleArticle);
                }
                //avis
                foreach (var avis in res.DerniersAvis)
                {
                    var index = avis.CleArticle.LastIndexOf("-");
                    string numeroCertificat = string.Empty;
                    if (index >= 0)
                    {
                        numeroCertificat = avis.CleArticle.Substring(0, index);
                    }
                    avis.UrlArticle = route.Url.Replace("{reference}", numeroCertificat).Replace("{numeroCertificat}-{articleID}", avis.CleArticle);
                }
            }

            return res;
        }
    }
}
