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

namespace DressAtelierDatabaseImplementation.Implements
{
    public class MaterialStorage : IMaterialStorage
    {

        public List<MaterialViewModel> GetFullList()
        {
            using var context = new DressAtelierDatabase();
            return context.Materials.Select(x => x.GetViewModel).ToList();
        }
        public List<MaterialViewModel> GetFilteredList(MaterialSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ComponentName))
            {
                return new();
            }

            using var context = new DressAtelierDatabase();
            return context.Materials.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList();  
        }

        public MaterialViewModel? GetElement(MaterialSearchModel model)
        {
            if (string.IsNullOrEmpty(model.ComponentName) && !model.ID.HasValue)
            {
                return null;
            }

            using var context = new DressAtelierDatabase();
            return context.Materials.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
        }

        public MaterialViewModel? Insert(MaterialBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var newComponent = Material.Create(model);
            if (newComponent == null)
            {
                return null;
            }

            context.Materials.Add(newComponent);
            context.SaveChanges();
            return newComponent.GetViewModel;
        }

        public MaterialViewModel? Update(MaterialBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var material = context.Materials.FirstOrDefault(x => x.ID == model.ID);
            if(material == null)
            {
                return null;
            }
            material.Update(model);
            context.SaveChanges();
            return material.GetViewModel;    
        }

        public MaterialViewModel? Delete(MaterialBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var material = context.Materials.FirstOrDefault(x => x.ID == model.ID);
            if(material == null)
            {
                return null;
            }
            context.Materials.Remove(material);
            context.SaveChanges();
            return material.GetViewModel;
        }

    }
}
