using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using EnumsNET;
using AyaNova.Util;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Models;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace AyaNova.Biz
{
    internal class NotifySubscriptionBiz : BizObject//, IJobObject, ISearchAbleObject
    {
        internal NotifySubscriptionBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
        {
            ct = dbcontext;
            UserId = currentUserId;
            UserTranslationId = userTranslationId;
            CurrentUserRoles = UserRoles;
            BizType = AyaType.NotifySubscription;
        }

        internal static NotifySubscriptionBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null)
        {
            if (httpContext != null)
                return new NotifySubscriptionBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items));
            else
                return new NotifySubscriptionBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdminFull);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //EXISTS 
        internal async Task<bool> ExistsAsync(long id)
        {
            return await ct.NotifySubscription.AnyAsync(z => z.Id == id);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //CREATE   
        //
        internal async Task<NotifySubscription> CreateAsync(NotifySubscription newObject)
        {
            await ValidateAsync(newObject);
            if (HasErrors)
                return null;
            else
            {
                newObject.Tags = TagBiz.NormalizeTags(newObject.Tags);

                await ct.NotifySubscription.AddAsync(newObject);
                await ct.SaveChangesAsync();
                await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
                await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null);
                return newObject;
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //DUPLICATE
        //
        internal async Task<NotifySubscription> DuplicateAsync(long id)
        {

            NotifySubscription dbObject = await GetAsync(id, false);
            if (dbObject == null)
            {
                AddError(ApiErrorCode.NOT_FOUND, "id");
                return null;
            }
            NotifySubscription newObject = new NotifySubscription();
            CopyObject.Copy(dbObject, newObject);

            newObject.Id = 0;
            newObject.Concurrency = 0;
            await ct.NotifySubscription.AddAsync(newObject);
            await ct.SaveChangesAsync();
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
            //await SearchIndexAsync(newObject, true);
            await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null);
            return newObject;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        // GET 
        //           
        internal async Task<NotifySubscription> GetAsync(long id, bool logTheGetEvent = true)
        {
            var ret = await ct.NotifySubscription.SingleOrDefaultAsync(z => z.Id == id && z.UserId == UserId);
            if (logTheGetEvent && ret != null)
                await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct);
            return ret;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //UPDATE
        //
        internal async Task<NotifySubscription> PutAsync(NotifySubscription putObject)
        {
            //TODO: Must remove all prior events and replace them 

            NotifySubscription dbObject = await ct.NotifySubscription.SingleOrDefaultAsync(z => z.Id == putObject.Id);
            if (dbObject == null)
            {
                AddError(ApiErrorCode.NOT_FOUND, "id");
                return null;
            }
            NotifySubscription SnapshotOfOriginalDBObj = new NotifySubscription();
            CopyObject.Copy(dbObject, SnapshotOfOriginalDBObj);
            CopyObject.Copy(putObject, dbObject, "Id");//can update serial
            dbObject.Tags = TagBiz.NormalizeTags(dbObject.Tags);

            ct.Entry(dbObject).OriginalValues["Concurrency"] = putObject.Concurrency;
            await ValidateAsync(dbObject);
            if (HasErrors) return null;
            try
            {
                await ct.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await ExistsAsync(putObject.Id))
                    AddError(ApiErrorCode.NOT_FOUND);
                else
                    AddError(ApiErrorCode.CONCURRENCY_CONFLICT);
                return null;
            }
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct);
            await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, dbObject.Tags, SnapshotOfOriginalDBObj.Tags);
            return dbObject;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //DELETE
        //
        internal async Task<bool> DeleteAsync(long id)
        {

            using (var transaction = await ct.Database.BeginTransactionAsync())
            {
                try
                {
                    NotifySubscription dbObject = await ct.NotifySubscription.SingleOrDefaultAsync(z => z.Id == id);
                    //ValidateCanDelete(dbObject);
                    if (HasErrors)
                        return false;
                    if (HasErrors)
                        return false;
                    ct.NotifySubscription.Remove(dbObject);
                    await ct.SaveChangesAsync();

                    //Log event 
                    await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.EventType.ToString(), ct);
                    // await Search.ProcessDeletedObjectKeywordsAsync(dbObject.Id, BizType, ct);
                    await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags);
                    //await FileUtil.DeleteAttachmentsForObjectAsync(BizType, dbObject.Id, ct);
                    //TODO: DELETE RELATED RECORDS HERE

                    //all good do the commit
                    await transaction.CommitAsync();
                }
                catch
                {
                    //Just re-throw for now, let exception handler deal, but in future may want to deal with this more here
                    throw;
                }
                return true;
            }
        }



        ////////////////////////////////////////////////////////////////////////////////////////////////
        //VALIDATION
        //
        private async Task ValidateAsync(NotifySubscription proposedObj)
        {

            //###############################################################################
            //todo: validate subscription is valid
            //perhaps check if customer type user doesn't have non customer notification etc

            //todo: notifysubscriptionbiz	Check for duplicate before accepting new / edit in validator
            //DISALLOW entirely duplicate notifications (down to email address)
            //USE NAME DUPE CHECK PATTERN BELOW 
            //###############################################################################

            //ensure user exists and need it for other shit later
            var user = await ct.User.AsNoTracking().FirstOrDefaultAsync(z => z.Id == proposedObj.UserId);
            if (user == null)
            {
                AddError(ApiErrorCode.VALIDATION_REQUIRED, "UserId");
            }
            else
            {

                //Validate user can see this subscription type
                if (user.UserType == UserType.Customer || user.UserType == UserType.HeadOffice)
                {
                    //Outside users can't choose inside user type notification events
                    switch (proposedObj.EventType)
                    {
                        case NotifyEventType.CSRAccepted:
                        case NotifyEventType.CSRRejected:
                        case NotifyEventType.CustomerServiceImminent:
                            break;
                        default:
                            AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "EventType");
                            break;
                    }
                }
                else
                {
                    //Inside users can't use Outside (customer) users notification types
                    switch (proposedObj.EventType)
                    {
                        case NotifyEventType.CSRAccepted:
                        case NotifyEventType.CSRRejected:
                        case NotifyEventType.CustomerServiceImminent:
                            AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "EventType");
                            break;
                        default:
                            break;
                    }

                }
            }



            //NOTE: In DB schema only name and serial are not nullable

            //run validation and biz rules

            // //Name required
            // if (string.IsNullOrWhiteSpace(proposedObj.Name))
            //     AddError(ApiErrorCode.VALIDATION_REQUIRED, "Name");

            // //Name must be less than 255 characters
            // if (proposedObj.Name.Length > 255)
            //     AddError(ApiErrorCode.VALIDATION_LENGTH_EXCEEDED, "Name", "255 max");

            // //If name is otherwise OK, check that name is unique
            // if (!PropertyHasErrors("Name"))
            // {
            //     //Use Any command is efficient way to check existance, it doesn't return the record, just a true or false
            //     if (await ct.NotifySubscription.AnyAsync(z => z.Name == proposedObj.Name && z.Id != proposedObj.Id))
            //     {
            //         AddError(ApiErrorCode.VALIDATION_NOT_UNIQUE, "Name");
            //     }
            // }

            // //Start date AND end date must both be null or both contain values
            // if (proposedObj.StartDate == null && proposedObj.EndDate != null)
            //     AddError(ApiErrorCode.VALIDATION_REQUIRED, "StartDate");

            // if (proposedObj.StartDate != null && proposedObj.EndDate == null)
            //     AddError(ApiErrorCode.VALIDATION_REQUIRED, "EndDate");

            // //Start date before end date
            // if (proposedObj.StartDate != null && proposedObj.EndDate != null)
            //     if (proposedObj.StartDate > proposedObj.EndDate)
            //         AddError(ApiErrorCode.VALIDATION_STARTDATE_AFTER_ENDDATE, "StartDate");

            // //Enum is valid value            
            // if (!proposedObj.UserType.IsValid())
            // {
            //     AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "UserType");
            // }

            // //Any form customizations to validate?
            // var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(z => z.FormKey == AyaType.NotifySubscription.ToString());
            // if (FormCustomization != null)
            // {
            //     //Yeppers, do the validation, there are two, the custom fields and the regular fields that might be set to required

            //     //validate users choices for required non custom fields
            //     RequiredFieldsValidator.Validate(this, FormCustomization, proposedObj);

            //     //validate custom fields
            //     CustomFieldsValidator.Validate(this, FormCustomization, proposedObj.CustomFields);
            // }
        }

        // private void ValidateCanDelete(NotifySubscription inObj)
        // {
        //     //whatever needs to be check to delete this object
        // }



        // ////////////////////////////////////////////////////////////////////////////////////////////////
        // //JOB / OPERATIONS
        // //
        // public async Task HandleJobAsync(OpsJob job)
        // {
        //     //Hand off the particular job to the corresponding processing code
        //     //NOTE: If this code throws an exception the caller (JobsBiz::ProcessJobsAsync) will automatically set the job to failed and log the exeption so 
        //     //basically any error condition during job processing should throw up an exception if it can't be handled
        //     switch (job.JobType)
        //     {
        //         case JobType.BulkCoreBizObjectOperation:
        //             await ProcessBulkJobAsync(job);
        //             break;
        //         default:
        //             throw new System.ArgumentOutOfRangeException($"NotifySubscriptionBiz.HandleJob-> Invalid job type{job.JobType.ToString()}");
        //     }
        // }



        // private async Task ProcessBulkJobAsync(OpsJob job)
        // {
        //     await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Running);
        //     await JobsBiz.LogJobAsync(job.GId, $"Bulk job {job.SubType} started...");
        //     List<long> idList = new List<long>();
        //     long ProcessedObjectCount = 0;
        //     JObject jobData = JObject.Parse(job.JobInfo);
        //     if (jobData.ContainsKey("idList"))
        //         idList = ((JArray)jobData["idList"]).ToObject<List<long>>();
        //     else
        //         idList = await ct.NotifySubscription.Select(z => z.Id).ToListAsync();
        //     bool SaveIt = false;
        //     foreach (long id in idList)
        //     {
        //         try
        //         {
        //             SaveIt = false;
        //             ClearErrors();
        //             var o = await GetAsync(id, false);
        //             switch (job.SubType)
        //             {
        //                 case JobSubType.TagAddAny:
        //                 case JobSubType.TagAdd:
        //                 case JobSubType.TagRemoveAny:
        //                 case JobSubType.TagRemove:
        //                 case JobSubType.TagReplaceAny:
        //                 case JobSubType.TagReplace:
        //                     SaveIt = TagBiz.ProcessBulkTagOperation(o.Tags, (string)jobData["tag"], jobData.ContainsKey("toTag") ? (string)jobData["toTag"] : null, job.SubType);
        //                     break;
        //                 default:
        //                     throw new System.ArgumentOutOfRangeException($"ProcessBulkJob -> Invalid job Subtype{job.SubType}");
        //             }
        //             if (SaveIt)
        //             {
        //                 o = await PutAsync(o);
        //                 if (o == null)
        //                     await JobsBiz.LogJobAsync(job.GId, $"Error processing item {id}: {GetErrorsAsString()}");
        //                 else
        //                     ProcessedObjectCount++;
        //             }
        //             else
        //                 ProcessedObjectCount++;
        //         }
        //         catch (Exception ex)
        //         {
        //             await JobsBiz.LogJobAsync(job.GId, $"Error processing item {id}");
        //             await JobsBiz.LogJobAsync(job.GId, ExceptionUtil.ExtractAllExceptionMessages(ex));
        //         }
        //     }
        //     await JobsBiz.LogJobAsync(job.GId, $"Bulk job {job.SubType} processed {ProcessedObjectCount} of {idList.Count}");
        //     await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Completed);
        // }


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

    }//eoc


}//eons

