using FishFactoryContracts.BindingModels;
using FishFactoryContracts.SearchModels;
using FishFactoryContracts.StoragesContracts;
using FishFactoryContracts.ViewModels;
using FishFactoryFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FishFactoryFileImplement.Implements
{
    public class OrderStorage : IOrderStorage
    {
        private readonly DataFileSingleton source;
        public OrderStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public List<OrderViewModel> GetFullList()
        {
            return source.Orders.Select(x => AcessDressesStorage(x.GetViewModel)).ToList();
        }
        public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
        {
            if (model.Id.HasValue)
                return source.Orders.Where(x => x.Id == model.Id).Select(x => AcessDressesStorage(x.GetViewModel)).ToList();
            else
            return source.Orders.Where(x => x.DateCreate >= model.DateFrom).Where(x => x.DateCreate <= model.DateTo).Select(x => AcessDressesStorage(x.GetViewModel)).ToList();
        }
        public OrderViewModel? GetElement(OrderSearchModel model)
        {
            if (!model.Id.HasValue)
            {
                return null;
            }
            return source.Orders.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }
        public OrderViewModel? Insert(OrderBindingModel model)
        {
            model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
            var newOrder = Order.Create(model);
            if (newOrder == null)
            {
                return null;
            }
            source.Orders.Add(newOrder);
            source.SaveOrders();
            return newOrder.GetViewModel;
        }
        public OrderViewModel? Update(OrderBindingModel model)
        {
            var component = source.Orders.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            source.SaveOrders();
            return component.GetViewModel;
        }
        public OrderViewModel? Delete(OrderBindingModel model)
        {
            var component = source.Orders.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            source.Orders.Remove(component);
            source.SaveOrders();
            return component.GetViewModel;
        }
        public OrderViewModel AcessDressesStorage(OrderViewModel model)
        {
            var component = source.Canneds.FirstOrDefault(x => x.Id == model.CannedId);
            model.CannedName = component.CannedName;
            return model;
        }
    }
}
