using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.JsonPatch;
using EnumsNET;
using AyaNova.Util;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;
using AyaNova.Models;


namespace AyaNova.Biz
{


    internal class JobOperationsBiz : BizObject
    {

        internal JobOperationsBiz(AyContext dbcontext, long currentUserId, AuthorizationRoles userRoles)
        {
            ct = dbcontext;
            UserId = currentUserId;
            CurrentUserRoles = userRoles;
            BizType=AyaType.JobOperations;
        }



        #region CONTROLLER ROUTES SUPPORT

        ////////////////////////////////////////////////////////////////////////////////////////////////
        /// GET

        //Get list of jobs
        internal async Task<List<JobOperationsFetchInfo>> GetJobListAsync()
        {
            List<JobOperationsFetchInfo> ret = new List<JobOperationsFetchInfo>();

            var jobitems = await ct.OpsJob
                            .OrderBy(m => m.Created)
                           .ToListAsync();

            foreach (OpsJob i in jobitems)
            {
                //fetch the most recent log time for each job 
                var mostRecentLogItem = await ct.OpsJobLog
                .Where(c => c.JobId == i.GId)
                .OrderByDescending(t => t.Created)
                .FirstOrDefaultAsync();

                JobOperationsFetchInfo o = new JobOperationsFetchInfo();
                if (mostRecentLogItem != null)
                    o.LastAction = mostRecentLogItem.Created;
                else
                    o.LastAction = i.Created;

                o.Created = i.Created;
                o.GId = i.GId;
                o.JobStatus = i.JobStatus.ToString();
                o.Name = i.Name;
                ret.Add(o);
            }

            return ret;
        }



        //Get list of logs for job
        internal async Task<List<JobOperationsLogInfoItem>> GetJobLogListAsync(Guid jobId)
        {
            List<JobOperationsLogInfoItem> ret = new List<JobOperationsLogInfoItem>();

            var l = await ct.OpsJobLog
                            .Where(c => c.JobId == jobId)
                            .OrderBy(m => m.Created)
                            .ToListAsync();

            foreach (OpsJobLog i in l)
            {

                JobOperationsLogInfoItem o = new JobOperationsLogInfoItem();

                o.Created = i.Created;
                o.StatusText = i.StatusText;
                ret.Add(o);
            }

            return ret;
        }

        #endregion controller routes




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

    }//eoc


}//eons

