using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Performance.Services
{
    public class TaskService : IAutoInjection
    {
        private readonly PerforBgtaskRepository _taskRepository;

        public TaskService(
            PerforBgtaskRepository taskRepository)
        {
            _taskRepository = taskRepository;
        }

        /// <summary>
        /// 默认返回 最近10小时的任务
        /// </summary> 
        /// <param name="hours"></param>
        /// <returns></returns>
        public List<bg_task> GetTasks(int hours = -10)
        {
            return _taskRepository.GetEntities(w => w.CreateTime > DateTime.Now.AddHours(hours));
        }

        public bool Add(Background.JobType type, string argument = "")
        {
            return _taskRepository.Add(new bg_task
            {
                Name = type.ToString(),
                JobType = (int)type,
                CreateTime = DateTime.Now,
                Argument = argument,
                Status = (int)Background.Status.等待,
                Remark = $"{type} - {Background.Status.等待}"
            });
        }

        public bool Update(int taskId, Background.Status status, string remark = "", double seconds = 0)
        {
            var task = _taskRepository.GetEntity(w => w.ID == taskId);
            if (task == null) return false;

            task.Status = (int)status;
            if (status == Background.Status.执行中)
                task.BeginTime = DateTime.Now;
            task.ElapsedTime = seconds;
            task.Remark = $"{(Background.JobType)task.JobType} - {status} {remark}";
            if (status == Background.Status.完成 || status == Background.Status.失败 || status == Background.Status.超时)
                task.EndTime = DateTime.Now;

            return _taskRepository.Update(task);
        }
    }
}
