using DressAtelierContracts.BindingModels;
using DressAtelierContracts.SearchModels;
using DressAtelierContracts.StorageContracts;
using DressAtelierContracts.ViewModels;
using DressAtelierDatabaseImplement.Models;
using DressAtelierDatabaseImplementation;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DressAtelierDatabaseImplement.Implements
{
    public class EmployeeStorage : IEmployeeStorage
    {
        public EmployeeViewModel? Insert(EmployeeBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var newEmployee = Employee.Create(model);
            context.Employees.Add(newEmployee);
            context.SaveChanges();
            return newEmployee.GetViewModel;
        }

        public EmployeeViewModel? Update(EmployeeBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var employee = context.Employees.FirstOrDefault(x => x.ID == model.ID);
            if(employee == null)
            {
                return null;
            }
            employee.Update(model);
            context.SaveChanges();
            return employee.GetViewModel;
        }

        public EmployeeViewModel? Delete(EmployeeBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var employee = context.Employees.FirstOrDefault(x => x.ID == model.ID);
            if(employee == null) { return null; }
            context.Employees.Remove(employee);
            context.SaveChanges();
            return employee.GetViewModel;
        }

        public List<EmployeeViewModel> GetFullList()
        {
            using var context = new DressAtelierDatabase();
            return context.Employees.Select(x => x.GetViewModel).ToList();
        }

        public EmployeeViewModel? GetElement(EmployeeSearchModel model)
        {
            if(string.IsNullOrEmpty(model.FullName) && !model.ID.HasValue)
            {
                return null;
            }
            using var context = new DressAtelierDatabase();
            return context.Employees.FirstOrDefault(x => (!string.IsNullOrEmpty(model.FullName) && x.FullName.Contains(model.FullName)) || (model.ID.HasValue && model.ID == x.ID))?.GetViewModel;
        }

        public List<EmployeeViewModel> GetFilteredList(EmployeeSearchModel model)
        {
            if (string.IsNullOrEmpty(model.FullName))
            {
                return new();
            }
            using var context = new DressAtelierDatabase();
            return context.Employees.Where(x => x.FullName.Equals(model.FullName)).Select(x => x.GetViewModel).ToList();
        }
    }
}
