using SushiBarContracts.BindingModel;
using SushiBarContracts.SearchModel;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using SushiBarFileImplement.Models;

namespace SushiBarFileImplement.Implements
{
    public class MessageInfoStorage : IMessageInfoStorage
    {
        private readonly DataFileSingleton source;
        public MessageInfoStorage()
        {
            source = DataFileSingleton.GetInstance();
        }

        public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
        {
            if (string.IsNullOrEmpty(model.MessageId)) return null;
            return source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId))?.GetViewModel;
        }

        public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
        {
            if (!model.ClientId.HasValue)
            {
                return new();
            }
            return source.Messages.Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList();
        }

        public List<MessageInfoViewModel> GetFullList()
        {
            return source.Messages.Select(x => x.GetViewModel).ToList();
        }

        public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
        {
            var newMessage = MessageInfo.Create(model);
            if(newMessage == null)
            {
                return null;
            }
            source.Messages.Add(newMessage);
            source.SaveMessageInfo();
            return newMessage.GetViewModel;
        }
    }
}
