using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemFileImplement.Models;

namespace SecuritySystemFileImplement.Implements
{
    public class MessageInfoStorage : IMessageInfoStorage
    {
        private DataFileSingleton _source;
        public MessageInfoStorage()
        {
            _source = DataFileSingleton.GetInstance();
        }

        public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
        {
            return GetFilteredList(model).FirstOrDefault();
        }

        public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
        {
            var messageInfos = GetFullList();
            if (!string.IsNullOrEmpty(model.MessageId))
            {
                messageInfos = messageInfos.Where(x => x.MessageId == model.MessageId).ToList();
            }
            if (model.ClientId != null)
            {
                messageInfos = messageInfos.Where(x => x.ClientId == model.ClientId).ToList();
            }
            return messageInfos;
        }

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

        public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
        {
            var messageInfo = MessageInfo.Create(model);
            if (messageInfo == null)
            {
                return null;
            }
            _source.MessageInfos.Add(messageInfo);
            _source.SaveMessageInfos();
            return messageInfo.GetViewModel;
        }
    }
}
