using CarCenterContracts.BindingModels;
using CarCenterContracts.SearchModels;
using CarCenterContracts.StoragesContracts;
using CarCenterContracts.ViewModels;
using CarCenterContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace CarCenterBusinessLogic.BusinessLogics
{
    public class AdministratorLogic : IAdministratorLogic
    {
        private readonly int _loginMaxLength = 50;
        private readonly int _passwordMaxLength = 50;
        private readonly int _passwordMinLength = 5;

        private readonly ILogger _logger;
        private readonly IAdministratorStorage _administratorStorage;

        public AdministratorLogic(ILogger<AdministratorLogic> logger, IAdministratorStorage administratorStorage)
        {
            _logger = logger;
            _administratorStorage = administratorStorage;
        }

        public bool Create(AdministratorBindingModel model)
        {
            CheckModel(model);

            if (_administratorStorage.Insert(model) == null)
            {
                _logger.LogWarning("Insert operation failed");

                return false;
            }

            return true;
        }

        public bool Delete(AdministratorBindingModel model)
        {
            CheckModel(model, false);

            _logger.LogInformation("Delete. Id: {Id}", model.Id);

            if (_administratorStorage.Delete(model) == null)
            {
                _logger.LogWarning("Delete operation failed");

                return false;
            }

            return true;
        }

        public AdministratorViewModel? ReadElement(AdministratorSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            _logger.LogInformation("ReadElement. AdministratorFIO: {AdministratorFIO}. AdministratorLogin: {AdministratorLogin}. Id: {Id}.", model.AdministratorFIO, model.AdministratorLogin, model.Id);

            var element = _administratorStorage.GetElement(model);

            if (element == null)
            {
                _logger.LogWarning("ReadElement element not found");
                return null;
            }

            _logger.LogInformation("ReadElement find. Id: {Id}", element.Id);

            return element;
        }

        public List<AdministratorViewModel>? ReadList(AdministratorSearchModel? model)
        {
            _logger.LogInformation("ReadList. AdministratorFIO: {AdministratorFIO}. AdministratorLogin: {AdministratorLogin}. Id: {Id}.", model?.AdministratorFIO, model?.AdministratorLogin, model?.Id);

            var list = model == null ? _administratorStorage.GetFullList() : _administratorStorage.GetFilteredList(model);

            if (list == null)
            {
                _logger.LogWarning("ReadList return null list");
                return null;
            }

            _logger.LogInformation("ReadList. Count: {Count}", list.Count);

            return list;
        }

        public bool Update(AdministratorBindingModel model)
        {
            CheckModel(model);

            if (_administratorStorage.Update(model) == null)
            {
                _logger.LogWarning("Update operation failed");
                return false;
            }
            return true;
        }

        private void CheckModel(AdministratorBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!withParams)
            {
                return;
            }

            if (string.IsNullOrEmpty(model.AdministratorFIO))
            {
                throw new ArgumentNullException("Нет ФИО администратора", nameof(model.AdministratorFIO));
            }

            if (string.IsNullOrEmpty(model.AdministratorLogin))
            {
                throw new ArgumentNullException("Нет логина администратора", nameof(model.AdministratorLogin));
            }

            if (model.AdministratorLogin.Length > _loginMaxLength)
            {
                throw new ArgumentNullException("Логин слишком длинный", nameof(model.AdministratorLogin));
            }

            if (string.IsNullOrEmpty(model.AdministratorNumber))
            {
                throw new ArgumentNullException("Нет номера телефона администратора", nameof(model.AdministratorNumber));
            }

			if (model.AdministratorEmail.Length > _loginMaxLength || !Regex.IsMatch(model.AdministratorEmail, @"([a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+)"))
			{
				throw new Exception($"В качестве логина должна быть указана почта и иметь длинну не более {_loginMaxLength} символов");
			}

			if (string.IsNullOrEmpty(model.AdministratorEmail))
            {
                throw new ArgumentNullException("Нет почты администратора", nameof(model.AdministratorEmail));
            }

            if (string.IsNullOrEmpty(model.AdministratorPassword))
            {
                throw new ArgumentNullException("Нет пароля администратора", nameof(model.AdministratorPassword));
            }

			if (model.AdministratorPassword.Length > _passwordMaxLength || model.AdministratorPassword.Length < _passwordMinLength
						   || !Regex.IsMatch(model.AdministratorPassword, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$"))
			{
				throw new Exception($"Пароль длиной от {_passwordMinLength} до {_passwordMaxLength} должен состоять из цифр, букв и небуквенных символов");
			}

            _logger.LogInformation("Administrator. AdministratorFIO: {AdministratorFIO}. AdministratorLogin: {AdministratorLogin}. Id: {Id}", model.AdministratorFIO, model.AdministratorLogin, model.Id);

            var element = _administratorStorage.GetElement(new AdministratorSearchModel
            {
                AdministratorEmail = model.AdministratorEmail
            });

            if (element != null && element.Id != model.Id)
            {
                throw new InvalidOperationException("администратор с таким логином уже есть");
            }
        }
    }
}
