using System;
using AutoMapper;
using Qusion.Cms.Core.Domain;
using Qusion.Cms.Modules.Blogs.Core;
using Qusion.Cms.Modules.Blogs.Domain;
using Qusion.Framework;

namespace Qusion.WebApp.Areas.Qusion.Models.Blogs
{
    /// <summary>
    /// Auto mapping from domain to models classes and vice versa
    /// </summary>
    public class BlogProfile : Profile
    {
        private readonly BlogService _blogService;

        public BlogProfile(BlogService blogService)
        {
            _blogService = blogService;
        }

        protected override void Configure()
        {
            CreateMap<Blog, BlogListModel>();
            CreateMap<Blog, BlogModel>();
            CreateMap<BlogCreateModel, Blog>();

            CreateMap<BlogPost, BlogPostListModel>()
                .ForMember(x => x.BlogID, o => o.MapFrom(x => x.Blog.ID));

            CreateMap<PostCreateModel, BlogPost>()
                .ForMember(x => x.Labels, o => o.Ignore())
                .ForMember(x => x.Status, o => o.MapFrom(x => Enumeration.FromValue<WorkflowStatus>(x.Status)));

            CreateMap<BlogEditModel, Blog>()
                .AfterMap(EditStatuses);

            CreateMap<BlogPost, PostModel>()
                .ForMember(x => x.Status, o => o.MapFrom(x => x.Status.Value))
                .ForMember(x => x.BlogID, o => o.MapFrom(x => x.Blog.GuidID));

            CreateMap<PostEidtModel, BlogPost>()
                .ForMember(x => x.Labels, o => o.Ignore())
                .ForMember(x => x.Status, o => o.MapFrom(x => Enumeration.FromValue<WorkflowStatus>(x.Status)));

            CreateMap<BlogPost, PostEidtModel>()
                .ForMember(x => x.Status, o => o.Ignore());

            CreateMap<BlogQueryInput, BlogQuery>()
                .ConstructUsing(x => BlogQuery.Default);

            CreateMap<BlogPostQueryInput, BlogPostQuery>()
                .ConstructUsing(x => BlogPostQuery.Default);
        }

        protected void EditStatuses(BlogEditModel model, Blog blog)
        {
            if (blog.ExpiresOn > DateTime.Today && blog.Posts.Count > 0)
                blog.Status = WorkflowStatus.Live;

            else if (!(blog.ExpiresOn > DateTime.Today))
            {
                blog.Status = WorkflowStatus.Archived;
            }

            else if (blog.ExpiresOn > DateTime.Today)
            {
                blog.Status = WorkflowStatus.Draft;
            }
        }
    }
}