using CanteenContracts.BindingModels;
using CanteenContracts.SearchModel;
using CanteenContracts.StoragesContracts;
using CanteenContracts.View;
using CanteenDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CanteenDatabaseImplement.Implements
{
    public class VisitorStorage : IVisitorStorage
    {
        public VisitorViewModel? GetElement(VisitorSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password) && string.IsNullOrEmpty(model.PhoneNumber) && !model.Id.HasValue)
            {
                return null;
            }

            using var context = new CanteenDatabase();

            return context.Visitors.FirstOrDefault(x =>
            (!string.IsNullOrEmpty(model.Login) && x.Login == model.Login) ||
            (model.Id.HasValue && x.Id == model.Id)
            )?.GetViewModel;
        }

        public List<VisitorViewModel> GetFilteredList(VisitorSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Login))
            {
                return new();
            }

            using var context = new CanteenDatabase();

            return context.Visitors.Where(x => x.Login.Contains(model.Login)).Select(x => x.GetViewModel).ToList();
        }

        public List<VisitorViewModel> GetFullList()
        {
            using var context = new CanteenDatabase();
            return context.Visitors.Select(x => x.GetViewModel).ToList();
        }

        public VisitorViewModel? Insert(VisitorBindingModel model)
        {
            var newVisitor = Visitor.Create(model);
            if (newVisitor == null)
            {
                return null;
            }

            using var context = new CanteenDatabase();

            context.Visitors.Add(newVisitor);
            context.SaveChanges();

            return newVisitor.GetViewModel;
        }

        public VisitorViewModel? Update(VisitorBindingModel model)
        {
            using var context = new CanteenDatabase();

            var client = context.Visitors.FirstOrDefault(x => x.Id == model.Id);
            if (client == null)
            {
                return null;
            }

            client.Update(model);
            context.SaveChanges();

            return client.GetViewModel;
        }

        public VisitorViewModel? Delete(VisitorBindingModel model)
        {
            using var context = new CanteenDatabase();

            var client = context.Visitors.FirstOrDefault(x => x.Id == model.Id);
            if (client == null)
            {
                return null;
            }

            context.Visitors.Remove(client);
            context.SaveChanges();

            return client.GetViewModel;
        }
    }
}
