using BankContracts.BindingModels;
using BankContracts.SearchModels;
using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BankDatabaseImplement.Implements
{
    public class CurrencyStorage : ICurrencyStorage
    {
        public CurrencyViewModel? Delete(CurrencyBindingModel model)
        {
            using var context = new BankDatabase();
            var element = context.Currencies.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Currencies.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }

        public CurrencyViewModel? GetElement(CurrencySearchModel model)
        {
            if (!model.Id.HasValue)
            {
                return null;
            }
            using var context = new BankDatabase();
            return context.Currencies
            .FirstOrDefault(x => x.Id == model.Id)
            ?.GetViewModel;
        }

        public List<CurrencyViewModel> GetFilteredList(CurrencySearchModel model)
        {
            if (!model.Id.HasValue)
            {
                return new();
            }
            using var context = new BankDatabase();
            return context.Currencies
            .Where(x => x.Id == model.Id)
            .Select(x => x.GetViewModel)
            .ToList();
        }

        public List<CurrencyViewModel> GetFullList()
        {
            using var context = new BankDatabase();
            return context.Currencies
            .Select(x => x.GetViewModel)
            .ToList();
        }

        public CurrencyViewModel? Insert(CurrencyBindingModel model)
        {
            using var context = new BankDatabase();
            var newCurrency = Currency.Create(context, model);
            if (newCurrency == null)
            {
                return null;
            }
            context.Currencies.Add(newCurrency);
            context.SaveChanges();
            return newCurrency.GetViewModel;
        }

        public CurrencyViewModel? Update(CurrencyBindingModel model)
        {
            using var context = new BankDatabase();
            var currency = context.Currencies.FirstOrDefault(x => x.Id == model.Id);
            if (currency == null)
            {
                return null;
            }
            currency.Update(model);
            context.SaveChanges();
            return currency.GetViewModel;
        }
    }
}
