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 EducationStatusLogic : IEducationStatusLogic
    {
        private readonly IEducationStatusStorage _esStorage;

        public EducationStatusLogic(IEducationStatusStorage cardStorage)
        {
            _esStorage = cardStorage;
        }

        public bool Create(EducationStatusBindingModel model)
        {
            CheckModel(model);
            if (_esStorage.Insert(model) == null)
            {
                return false;
            }
            return true;
        }
        public bool Update(EducationStatusBindingModel model)
        {
            CheckModel(model);
            if (_esStorage.Update(model) == null)
            {
                return false;
            }
            return true;
        }
        public bool Delete(EducationStatusBindingModel model)
        {
            CheckModel(model, false);
            if (_esStorage.Delete(model) == null)
            {
                return false;
            }
            return true;
        }
        public EducationStatusViewModel? ReadElement(EducationStatusSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            var es = _esStorage.GetElement(model);
            if (es == null)
            {
                return null;
            }
            return es;
        }

        public List<EducationStatusViewModel>? ReadList(EducationStatusSearchModel? model)
        {
            var list = model == null ? _esStorage.GetFullList() : _esStorage.GetFilteredList(model);
            if (list == null)
            {
                return null;
            }
            return list;
        }

        private void CheckModel(EducationStatusBindingModel 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 es = _esStorage.GetElement(new EducationStatusSearchModel
            {
                Name = model.Name,
            });
            if (es != null && es.Id != model.Id)
            {
                throw new InvalidOperationException("Статус с таким названием уже есть");
            }
        }
    }
}
