using ShipyardContracts.BindingModels;
using ShipyardContracts.SearchModels;
using ShipyardContracts.StoragesContracts;
using ShipyardContracts.ViewModels;
using ShipyardFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShipyardFileImplement.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 == model.MessageId)?.GetViewModel;
        }

        public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
        {
            if (string.IsNullOrEmpty(model.MessageId))
            {
                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 = Message.Create(model);
            if (newMessage == null)
            {
                return null;
            }
            source.Messages.Add(newMessage);
            source.SaveMessages();
            return newMessage.GetViewModel;
        }
    }
}
