using AutoMapper;
using Kean.Application.Command.Interfaces;
using Kean.Application.Command.ViewModels;
using Kean.Domain;
using Kean.Domain.Basic.Commands;
using Kean.Domain.Stock.Commands;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Kean.Application.Command.Implements
{
    /// <summary>
    /// 命令服务实现
    /// </summary>
    public class InterfaceService : IInterfaceService
    {
        private readonly ICommandBus _bus; // 命令总线
        private readonly IMapper _mapper; // 模型映射
        private readonly INotification _notifications; // 总线通知
        private readonly ILogger<InterfaceService> _logger; // 日志

        /// <summary>
        /// 依赖注入
        /// </summary>
        public InterfaceService(
            ICommandBus bus,
            ILogger<InterfaceService> logger,
            IMapper mapper,
            INotification notifications)
        {
            _bus = bus;
            _logger = logger;
            _mapper = mapper;
            _notifications = notifications;
        }

        /*
         * 实现 Kean.Application.Command.Interfaces.IMaterialService.CreateMaterial 方法
         */
        public async Task<Failure> Append(InterfaceRecord interfaceRecorderial)
        {
            var command = _mapper.Map<InterfaceRecordCommand>(interfaceRecorderial);
            await _bus.Execute(command);
            return (_notifications.FirstOrDefault());
        }

        /*
         * 实现 Kean.Application.Command.Interfaces.IMaterialService.Clear 方法
         */
        public async Task<Failure> Clear(string addMonths)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            
            ClearRecordCommand command =  new ClearRecordCommand();
            command.AddMonth = Convert.ToInt32(addMonths);

            var hash = command.GetHashCode();
            _logger.LogInformation($"过程[{hash}]开始:清除记录:月份[{addMonths}]");

            await _bus.Execute(command);

            _logger.LogInformation("过程[{Hash}]结束:耗时{TimeSpan}ms。", hash, stopwatch.ElapsedMilliseconds);
            return (_notifications.FirstOrDefault());
        }

    }
}