using Knoks.Core.Data.Interfaces;
using Knoks.Core.Entities;
using Knoks.Core.Entities.Args;
using Knoks.Framework.DataAccess;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Knoks.Core.Data.Dao
{
    public class OperatorDao : IOperatorDao
    {
        private readonly IProcExecutor _executor;
        private readonly ILogger<OperatorDao> _logger;

        public OperatorDao(ILogger<OperatorDao> logger, IProcExecutor executor)
        {
            _logger = logger;
            _executor = executor;
        }

        public async Task<Operator> CreateOperator(CreateOperatorArgs args)
        {
            return (await _executor.Go("REG_CreateOperator", args)).Тables[0][0].To<Operator>();
        }

        public async Task<IEnumerable<Operator>> GetOperators(int? operatorId = null)
        {
            _logger.LogDebug("GetOperators : {0}", operatorId);
            return (await _executor.Go("REG_GetOperators", new { OperatorId = operatorId })).Тables[0].Rows.Select(row => row.To<Operator>());
        }

        public async Task<OperatorCredential> GetOperatorCredential(int apiConsumerId, string operatorName)
        {
            _logger.LogDebug($"GetOperatorCredential: {nameof(operatorName)}='{operatorName}'");

            var dataResult = await _executor.Go("REG_GetOperatorCredential", new { ApiConsumerId = apiConsumerId, OperatorName = operatorName });
            return dataResult.Тables[0].Rows.Count != 1 ? null : new OperatorCredential
            {
                Operator = dataResult.Тables[0][0].To<Operator>(),
                OperatorPassword = dataResult.OutputParams["OperatorPassword"].ToString()
            };
        }
    }
}
