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 WidgetBiz : BizObject, IJobObject, ISearchAbleObject, IReportAbleObject
    {


        internal WidgetBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
        {
            ct = dbcontext;
            UserId = currentUserId;
            UserTranslationId = userTranslationId;
            CurrentUserRoles = UserRoles;
            BizType = AyaType.Widget;
        }

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

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

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //CREATE   
        //
        internal async Task<Widget> CreateAsync(Widget newObject)
        {
            await ValidateAsync(newObject);
            if (HasErrors)
                return null;
            else
            {
                newObject.Tags = TagBiz.NormalizeTags(newObject.Tags);
                newObject.CustomFields = JsonUtil.CompactJson(newObject.CustomFields);
                await ct.Widget.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);
                await NotifyEventProcessor.HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
                return newObject;
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //DUPLICATE
        //
        internal async Task<Widget> DuplicateAsync(long id)
        {
            Widget dbObject = await GetAsync(id, false);
            if (dbObject == null)
            {
                AddError(ApiErrorCode.NOT_FOUND, "id");
                return null;
            }
            Widget newObject = new Widget();
            CopyObject.Copy(dbObject, newObject, "Wiki,Serial");
            string newUniqueName = string.Empty;
            bool NotUnique = true;
            long l = 1;
            do
            {
                newUniqueName = Util.StringUtil.UniqueNameBuilder(dbObject.Name, l++, 255);
                NotUnique = await ct.Widget.AnyAsync(z => z.Name == newUniqueName);
            } while (NotUnique);
            newObject.Name = newUniqueName;
            newObject.Id = 0;
            newObject.Concurrency = 0;
            await ct.Widget.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);
            await NotifyEventProcessor.HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
            return newObject;
        }

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

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //UPDATE
        //
        internal async Task<Widget> PutAsync(Widget putObject)
        {
            Widget dbObject = await ct.Widget.SingleOrDefaultAsync(z => z.Id == putObject.Id);
            if (dbObject == null)
            {
                AddError(ApiErrorCode.NOT_FOUND, "id");
                return null;
            }
            Widget SnapshotOfOriginalDBObj = new Widget();
            CopyObject.Copy(dbObject, SnapshotOfOriginalDBObj);
            CopyObject.Copy(putObject, dbObject, "Id");//can update serial
            dbObject.Tags = TagBiz.NormalizeTags(dbObject.Tags);
            dbObject.CustomFields = JsonUtil.CompactJson(dbObject.CustomFields);
            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 SearchIndexAsync(dbObject, false);
            await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, dbObject.Tags, SnapshotOfOriginalDBObj.Tags);
            await NotifyEventProcessor.HandlePotentialNotificationEvent(AyaEvent.Modified, dbObject, SnapshotOfOriginalDBObj);
            return dbObject;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //DELETE
        //
        internal async Task<bool> DeleteAsync(long id)
        {
            using (var transaction = await ct.Database.BeginTransactionAsync())
            {
                try
                {
                    Widget dbObject = await ct.Widget.SingleOrDefaultAsync(z => z.Id == id);
                    ValidateCanDelete(dbObject);
                    if (HasErrors)
                        return false;
                    if (HasErrors)
                        return false;
                    ct.Widget.Remove(dbObject);
                    await ct.SaveChangesAsync();

                    //Log event 
                    await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.Name, ct);
                    await Search.ProcessDeletedObjectKeywordsAsync(dbObject.Id, BizType, ct);
                    await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags);
                    await FileUtil.DeleteAttachmentsForObjectAsync(BizType, dbObject.Id, ct);
                    //all good do the commit
                    await transaction.CommitAsync();
                    await NotifyEventProcessor.HandlePotentialNotificationEvent(AyaEvent.Deleted, dbObject);
                }
                catch
                {
                    //Just re-throw for now, let exception handler deal, but in future may want to deal with this more here
                    throw;
                }
                return true;
            }
        }


        ////////////////////////////////////////////////////////////////////////////////////////////////
        //RESTART SERIAL
        //
        internal async Task<bool> RestartSerial(long newSerial)
        {
            using (var command = ct.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = $"alter table awidget alter column serial restart with {newSerial}";
                await ct.Database.OpenConnectionAsync();
                await command.ExecuteNonQueryAsync();
                await ct.Database.CloseConnectionAsync();
            }
            await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, 0, BizType, AyaEvent.ResetSerial, newSerial.ToString()), ct);
            return true;
        }


        ////////////////////////////////////////////////////////////////////////////////////////////////
        //SEARCH
        //
        private async Task SearchIndexAsync(Widget obj, bool isNew)
        {
            var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType);
            SearchParams.AddText(obj.Notes).AddText(obj.Name).AddText(obj.Serial).AddText(obj.Wiki).AddText(obj.Tags).AddCustomFields(obj.CustomFields);
            if (isNew)
                await Search.ProcessNewObjectKeywordsAsync(SearchParams);
            else
                await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams);
        }

        public async Task<Search.SearchIndexProcessObjectParameters> GetSearchResultSummary(long id)
        {
            var obj = await ct.Widget.SingleOrDefaultAsync(z => z.Id == id);
            var SearchParams = new Search.SearchIndexProcessObjectParameters();
            if (obj != null)
                SearchParams.AddText(obj.Notes).AddText(obj.Name).AddText(obj.Serial).AddText(obj.Wiki).AddText(obj.Tags).AddCustomFields(obj.CustomFields);
            return SearchParams;
        }


        ////////////////////////////////////////////////////////////////////////////////////////////////
        //VALIDATION
        //
        private async Task ValidateAsync(Widget proposedObj)
        {
            //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.Widget.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.Widget.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(Widget inObj)
        {
            //whatever needs to be check to delete this object
        }

        //Fulfil report request for data
        public async Task<JArray> GetReportData(long[] idList)
        {
            //NOTE: Report widget is a superset of biz object widget
            //Biz objects will add and needed linked records here as extra fields with the data included
            //for example instead of a userid only there will be username added to the record
            //so the report designer can just select it as a field, no need to query seperately for it etc
            //REMEMBER: there is a name display format system and it should honour that so that the report
            //displays a user the same as it would display in the UI in an input form, no surprises

            JArray ReportData = new JArray();
            while (idList.Any())
            {
                var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE);
                idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray();
                //query for this batch, comes back in db natural order unfortunately
                var batchResults = await ct.Widget.Where(z => batch.Contains(z.Id)).ToArrayAsync();
                //order the results back into original
                var orderedList = from id in batch join z in batchResults on id equals z.Id select z;
                foreach (Widget w in orderedList)
                {
                    var jo=JObject.FromObject(w);
                    jo["CustomFields"]=JObject.Parse((string)jo["CustomFields"]);
                    ReportData.Add(jo);
                }
            }
            return ReportData;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////
        //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($"WidgetBiz.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.Widget.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

