using DressAtelierContracts.BindingModels;
using DressAtelierContracts.SearchModels;
using DressAtelierContracts.StorageContracts;
using DressAtelierContracts.ViewModels;
using DressAtelierFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DressAtelierFileImplement.Implements
{
    public class EmployeeStorage : IEmployeeStorage
    {
        private readonly DataFileSingleton _source;

        public EmployeeStorage()
        {
            _source = DataFileSingleton.GetInstance();
        }
        public EmployeeViewModel? Insert(EmployeeBindingModel model)
        {
            model.ID = _source.Employees.Count > 0 ? _source.Employees.Max(client => client.ID) + 1 : 1;
            var newEmployee = Employee.Create(model);
            if (newEmployee == null) { return null; }
            _source.Employees.Add(newEmployee);
            _source.SaveEmployees();
            return newEmployee.GetViewModel;
        }

        public EmployeeViewModel? Update(EmployeeBindingModel model)
        {
            var employee = _source.Employees.FirstOrDefault(x => x.ID == model.ID);
            if (employee == null) { return null; };
            employee.Update(model);
            _source.SaveEmployees();
            return employee.GetViewModel;
        }
        public EmployeeViewModel? Delete(EmployeeBindingModel model)
        {
            var employee = _source.Employees.FirstOrDefault(employee => employee.ID == model.ID);
            if (employee == null) { return null; }
            _source.Employees.Remove(employee);
            _source.SaveEmployees();
            return employee.GetViewModel;
        }

        public EmployeeViewModel? GetElement(EmployeeSearchModel model)
        {
            if (string.IsNullOrEmpty(model.FullName) && !model.ID.HasValue) { return null; }

            return _source.Employees.FirstOrDefault(x => (!(string.IsNullOrEmpty(model.FullName)) && model.FullName == x.FullName) || (model.ID.HasValue && model.ID == x.ID))?.GetViewModel;
        }

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

        public List<EmployeeViewModel> GetFullList()
        {
            return _source.Employees.Select(x => x.GetViewModel).ToList();
        }
    }
}
