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


namespace AyaNova.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)
        {
            //System.Diagnostics.Debug.WriteLine($"Event log event for {newEvent.AyId}:{newEvent.AyaType} {newEvent.AyEvent} {newEvent.Created}");

            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="ayaType"></param>
        /// <param name="ayId"></param>
        /// <param name="textra"></param>
        /// <param name="ct"></param>
        internal static async Task DeleteObjectLogAsync(long userId, AyaType ayaType, long ayId, string textra, AyContext ct)
        {
            await ct.Database.ExecuteSqlInterpolatedAsync($"delete from aevent where ayatype = {ayaType} and ayid={ayId}");
            await ct.Event.AddAsync(new Event(userId, ayId, ayaType, AyaEvent.Deleted, $"{textra} (id {ayId})"));
            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<AyaNova.Api.Controllers.EventLogController.ObjectEventLog> GetLogForObjectAsync(AyaNova.Api.Controllers.EventLogController.EventLogOptions opt, AyContext ct)
        {
            AyaNova.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.AyId == opt.AyId && z.AyaType == opt.AyaType);
            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 AyaNova.Api.Controllers.EventLogController.ObjectEventLogItem()
                {
                    Date = z.Created,
                    UserId = z.UserId,
                    Event = z.AyEvent,
                    Textra = z.Textra,
                    Name = BizObjectNameFetcherDirect.Name(AyaType.User, z.UserId, command)
                }).ToArray();

                ret.Name = BizObjectNameFetcherDirect.Name(opt.AyaType, opt.AyId, 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<AyaNova.Api.Controllers.EventLogController.UserEventLog> GetLogForUserAsync(AyaNova.Api.Controllers.EventLogController.UserEventLogOptions opt, AyContext ct)
        {

            AyaNova.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 AyaNova.Api.Controllers.EventLogController.UserEventLogItem()
                {

                    Date = z.Created,
                    ObjectType = z.AyaType,
                    ObjectId = z.AyId,
                    Event = z.AyEvent,
                    Textra = z.Textra,
                    Name = BizObjectNameFetcherDirect.Name(z.AyaType, z.AyId, command)

                }).ToArray();
                ret.Name = BizObjectNameFetcherDirect.Name(AyaType.User, opt.UserId, 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(AyaNova.Api.Controllers.EventLogController.V7Event ev, AyContext ct)
        {
            //delete the automatically created entry from the exported object
            await ct.Database.ExecuteSqlInterpolatedAsync($"delete from aevent where ayatype = {ev.AyaType} 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.AyaType, AyaEvent.Created, ev.Created, null), ct);

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


            await ct.SaveChangesAsync();
        }



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


    }//eoc

}//eons

