using Kivii.Domain.Contents.Entities;
using Kivii.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kivii.Domain.Contents.Transforms
{
    [Route(Configs.RouteRedirect)]
    public class RedirectRequest
    {
        public string InternalCode { get; set; }
    }

    internal static class RedirectExtensions
    {
        public static object Excute(this Service service, RedirectRequest request)
        {
            if (request.InternalCode.IsNullOrEmpty()) return HttpError.NotFound("Need InternalCode!");

            var conn = KiviiContext.GetOpenedDbConnection<Redirect>();
            var redirect = conn.Single<Redirect>(o => o.InternalCode.ToLower() == request.InternalCode.ToLower());
            if (redirect == null) return HttpError.NotFound("Need Redirect Item!");
            if (!redirect.IsPublish) return HttpError.NotFound("This Item is Unannounced!");

            //访问数增加
            conn.UpdateAdd(() => new Redirect { Hits = 1 }, o => o.Kvid == redirect.Kvid);

            var session = service.GetSession();
            var guestLog = new GuestLog();
            guestLog.PopulateWith(session);
            guestLog.Kvid = Guid.NewGuid();
            guestLog.RedirectKvid = redirect.Kvid;
            guestLog.GuestTime = DateTime.Now;
            guestLog.Ip = service.Request.UserHostAddress;
            guestLog.UserAgent = service.Request.UserAgent;
            conn.Insert(guestLog);

            if (redirect.TemplatePath.IsNullOrEmpty()) return HttpResult.Redirect(redirect.Url);

            return new HttpResult
            {
                Response = redirect,
                View = redirect.TemplatePath
            };
        }
    }
}
