using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sockeye.Util;
using Sockeye.Api.ControllerHelpers;
using Sockeye.Models;
using System.Linq;

namespace Sockeye.Biz
{
    internal class CustomerNotifySubscriptionBiz : BizObject//, IJobObject, ISearchAbleObject
    {
        internal CustomerNotifySubscriptionBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
        {
            ct = dbcontext;
            UserId = currentUserId;
            UserTranslationId = userTranslationId;
            CurrentUserRoles = UserRoles;
            BizType = SockType.CustomerNotifySubscription;
        }

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

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

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

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


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

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

            var dbObject = await GetAsync(putObject.Id, false);
            if (dbObject == null)
            {
                AddError(ApiErrorCode.NOT_FOUND, "id");
                return null;
            }
            if (dbObject.Concurrency != putObject.Concurrency)
            {
                AddError(ApiErrorCode.CONCURRENCY_CONFLICT);
                return null;
            }
            putObject.CustomerTags = TagBiz.NormalizeTags(putObject.CustomerTags);
            putObject.Tags = TagBiz.NormalizeTags(putObject.Tags);
            ValidateAsync(putObject);
            if (HasErrors) return null;
            ct.Replace(dbObject, putObject);
            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, SockEvent.Modified), ct);
            await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, putObject.Tags, dbObject.Tags);
            await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, putObject.CustomerTags, dbObject.CustomerTags);
            return putObject;
        }

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

            using (var transaction = await ct.Database.BeginTransactionAsync())
            {
                var dbObject = await GetAsync(id, false);
                if (dbObject == null)
                {
                    AddError(ApiErrorCode.NOT_FOUND);
                    return false;
                }
                //ValidateCanDelete(dbObject);
                if (HasErrors)
                    return false;
                {
                    var IDList = await ct.Review.AsNoTracking().Where(x => x.SockType == SockType.CustomerNotifySubscription && x.ObjectId == id).Select(x => x.Id).ToListAsync();
                    if (IDList.Count() > 0)
                    {
                        ReviewBiz b = new ReviewBiz(ct, UserId, UserTranslationId, CurrentUserRoles);
                        foreach (long ItemId in IDList)
                            if (!await b.DeleteAsync(ItemId, transaction))
                            {
                                AddError(ApiErrorCode.CHILD_OBJECT_ERROR, null, $"Review [{ItemId}]: {b.GetErrorsAsString()}");
                                return false;
                            }
                    }
                }
                ct.CustomerNotifySubscription.Remove(dbObject);
                await ct.SaveChangesAsync();

                //Log event 
                await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.EventType.ToString(), ct);
                await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags);
                await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.CustomerTags);


                await transaction.CommitAsync();

                return true;
            }
        }



        ////////////////////////////////////////////////////////////////////////////////////////////////
        //VALIDATION
        //
        private void ValidateAsync(CustomerNotifySubscription proposedObj)
        {
            if (string.IsNullOrWhiteSpace(proposedObj.CurrencyName))
                AddError(ApiErrorCode.VALIDATION_REQUIRED, "CurrencyName");

            if (string.IsNullOrWhiteSpace(proposedObj.LanguageOverride))
                AddError(ApiErrorCode.VALIDATION_REQUIRED, "LanguageOverride");

            if (string.IsNullOrWhiteSpace(proposedObj.TimeZoneOverride))
                AddError(ApiErrorCode.VALIDATION_REQUIRED, "TimeZoneOverride");

            if (proposedObj.TranslationId == 0)
                AddError(ApiErrorCode.VALIDATION_REQUIRED, "TranslationId");



        }


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

    }//eoc


}//eons

