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

namespace UniversityBusinessLogic.BusinessLogics
{
    public class EducationGroupLogic
    {
        private readonly IEducationGroupStorage _egStorage;

        public EducationGroupLogic(IEducationGroupStorage cardStorage)
        {
            _egStorage = cardStorage;
        }

        public bool Create(EducationGroupBindingModel model)
        {
            CheckModel(model);
            if (_egStorage.Insert(model) == null)
            {
                return false;
            }
            return true;
        }
        public bool Update(EducationGroupBindingModel model)
        {
            CheckModel(model);
            if (_egStorage.Update(model) == null)
            {
                return false;
            }
            return true;
        }
        public bool Delete(EducationGroupBindingModel model)
        {
            CheckModel(model, false);
            if (_egStorage.Delete(model) == null)
            {
                return false;
            }
            return true;
        }
        public EducationGroupViewModel? ReadElement(EducationGroupSearchModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            var es = _egStorage.GetElement(model);
            if (es == null)
            {
                return null;
            }
            return es;
        }

        public List<EducationGroupViewModel>? ReadList(EducationGroupSearchModel? model)
        {
            var list = model == null ? _egStorage.GetFullList() : _egStorage.GetFilteredList(model);
            if (list == null)
            {
                return null;
            }
            return list;
        }

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