using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;

namespace UniversityBusinessLogic.BusinessLogics
{
    public class RoleLogic : IRoleLogic
    {
        private readonly IRoleStorage _roleStorage;
        public RoleLogic(IRoleStorage roleStorage)
        {
            _roleStorage = roleStorage;
        }
        public bool Create(RoleBindingModel model)
        {
            CheckModel(model);
            if (_roleStorage.Insert(model) == null)
            {
                return false;
            }
            return true;
        }

        public bool Delete(RoleBindingModel model)
        {
            CheckModel(model, false);
            if (_roleStorage.Delete(model) == null)
            {
                return false;
            }
            return true;
        }

        public RoleViewModel? ReadElement(RoleSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            var element = _roleStorage.GetElement(model);
            if (element == null)
            {
                return null;
            }
            return element;
        }

        public List<RoleViewModel>? ReadList(RoleSearchModel? model)
        {
            var list = model == null ? _roleStorage.GetFullList() : _roleStorage.GetFilteredList(model);
            if (list == null)
            {
                return null;
            }
            return list;
        }

        public bool Update(RoleBindingModel model)
        {
            CheckModel(model);
            if (_roleStorage.Update(model) == null)
            {
                return false;
            }
            return true;
        }

        private void CheckModel(RoleBindingModel model, bool withParams = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (!withParams)
            {
                return;
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException("Нет названия роли", nameof(model.Name));
            }

            var element = _roleStorage.GetElement(new RoleSearchModel
            {
                Name = model.Name
            });
            if (element != null && element.Id != model.Id)
            {
                throw new InvalidOperationException("Роль с таким названием уже есть");
            }
        }
    }
}
