using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sockeye.Models;
using System;


namespace Sockeye.Biz
{
    internal static class EventLogProcessor
    {
        private const int DEFAULT_EVENT_LIMIT = 20;

        /// <summary>
        /// Add an entry to the log
        /// 
        /// </summary>      
        /// <param name="newEvent"></param>
        /// <param name="ct"></param>
        /// <returns></returns>
        internal static async Task LogEventToDatabaseAsync(Event newEvent, AyContext ct)
        {
            await ct.Event.AddAsync(newEvent);
            await ct.SaveChangesAsync();
        }



        /// <summary>
        /// Handle delete
        /// remove all prior entries for object, add one deleted entry
        /// </summary>             
        /// <param name="userId"></param>
        /// <param name="sockType"></param>
        /// <param name="sockId"></param>
        /// <param name="textra"></param>
        /// <param name="ct"></param>
        internal static async Task DeleteObjectLogAsync(long userId, SockType sockType, long sockId, string textra, AyContext ct)
        {
            await ct.Database.ExecuteSqlInterpolatedAsync($"delete from aevent where socktype = {sockType} and sockid={sockId}");
            await ct.Event.AddAsync(new Event(userId, sockId, sockType, SockEvent.Deleted, $"{textra} (id {sockId})"));
            await ct.SaveChangesAsync();
        }

        /// <summary>
        /// Get the event log for a specified object
        /// Presentation is the client's responsibility (localization internationalization etc)
        /// </summary>
        internal static async Task<Sockeye.Api.Controllers.EventLogController.ObjectEventLog> GetLogForObjectAsync(Sockeye.Api.Controllers.EventLogController.EventLogOptions opt, long translationId, AyContext ct)
        {
            Sockeye.Api.Controllers.EventLogController.ObjectEventLog ret = new Api.Controllers.EventLogController.ObjectEventLog();

            var limit = opt.Limit ?? DEFAULT_EVENT_LIMIT;
            var offset = opt.Offset ?? 0;

            //Set up the query       
            var q = ct.Event.Select(z => z).AsNoTracking();
            q = q.Where(z => z.SockId == opt.AyId && z.SockType == opt.SockType);
            q = q.OrderByDescending(z => z.Created);
            q = q.Skip(offset).Take(limit);

            //Execute the query
            var EventItems = await q.ToArrayAsync();

            //convert the Event array to the correct return type array
            using (var command = ct.Database.GetDbConnection().CreateCommand())
            {
                ct.Database.OpenConnection();
                ret.Events = EventItems.Select(z => new Sockeye.Api.Controllers.EventLogController.ObjectEventLogItem()
                {
                    Date = z.Created,
                    UserId = z.UserId,
                    Event = z.SockEvent,
                    Textra = z.Textra,
                    Name = BizObjectNameFetcherDirect.Name(SockType.User, z.UserId, translationId, command)
                }).ToArray();

                ret.Name = BizObjectNameFetcherDirect.Name(opt.SockType, opt.AyId, translationId, command);
                return ret;
            }
        }



        /// <summary>
        /// Get the event log for a specified User
        /// Presentation is the client's responsibility (localization internationalization etc)
        /// </summary>
        internal static async Task<Sockeye.Api.Controllers.EventLogController.UserEventLog> GetLogForUserAsync(Sockeye.Api.Controllers.EventLogController.UserEventLogOptions opt, long translationId, AyContext ct)
        {

            Sockeye.Api.Controllers.EventLogController.UserEventLog ret = new Api.Controllers.EventLogController.UserEventLog();
            var limit = opt.Limit ?? DEFAULT_EVENT_LIMIT;
            var offset = opt.Offset ?? 0;
            //Set up the query


            var q = ct.Event.Select(z => z).AsNoTracking();
            q = q.Where(z => z.UserId == opt.UserId);
            q = q.OrderByDescending(z => z.Created);
            q = q.Skip(offset).Take(limit);


            //Execute the query
            var EventItems = await q.ToArrayAsync();
            using (var command = ct.Database.GetDbConnection().CreateCommand())
            {
                ct.Database.OpenConnection();
                //convert the Event array to the correct return type array
                ret.Events = EventItems.Select(z => new Sockeye.Api.Controllers.EventLogController.UserEventLogItem()
                {

                    Date = z.Created,
                    SockType = z.SockType,
                    ObjectId = z.SockId,
                    Event = z.SockEvent,
                    Textra = z.Textra,
                    Name = BizObjectNameFetcherDirect.Name(z.SockType, z.SockId, translationId, command)

                }).ToArray();
                ret.Name = BizObjectNameFetcherDirect.Name(SockType.User, opt.UserId, translationId, command);
                return ret;
            }

        }


        /// <summary>
        /// V7 export handler
        /// Exporter needs to fixup event log CREATED entry to show original created and last modified times
        /// and users
        /// </summary>                   
        internal static async Task V7_Modify_LogAsync(Sockeye.Api.Controllers.EventLogController.V7Event ev, AyContext ct)
        {
            //delete the automatically created entry from the exported object
            await ct.Database.ExecuteSqlInterpolatedAsync($"delete from aevent where socktype = {ev.SockType} and ayid={ev.AyId}");

            //Now create the entries to reflect the original data from v7
            //CREATED
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(ev.Creator, ev.AyId, ev.SockType, SockEvent.Created, ev.Created, null), ct);

            //MODIFIED
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(ev.Modifier, ev.AyId, ev.SockType, SockEvent.Modified, ev.Modified, null), ct);


            await ct.SaveChangesAsync();
        }



        /////////////////////////////////////////////////////////////////////


    }//eoc

}//eons

