package org.mercury_im.messenger.data.mapping;

import org.mercury_im.messenger.data.model.MessageModel;
import org.mercury_im.messenger.data.model.MessagePayloadContainerModel;
import org.mercury_im.messenger.entity.message.Message;
import org.mercury_im.messenger.entity.message.PayloadContainer;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class MessageMapping extends AbstractMapping<Message, MessageModel> {

    private final MessagePayloadContainerMapping messagePayloadContainerMapping;

    @Inject
    public MessageMapping(MessagePayloadContainerMapping messagePayloadContainerMapping) {
        this.messagePayloadContainerMapping = messagePayloadContainerMapping;
    }

    @Override
    public Message newEntity(MessageModel model) {
        return new Message();
    }

    @Override
    public MessageModel newModel(Message entity) {
        return new MessageModel();
    }

    @Override
    public MessageModel mapToModel(Message entity, MessageModel model) {
        model.setSender(entity.getSender());
        model.setRecipient(entity.getRecipient());
        model.setTimestamp(entity.getTimestamp());
        model.setDirection(entity.getDirection());

        model.getPayloads().clear();
        for (PayloadContainer payload : entity.getMessagePayloads()) {
            MessagePayloadContainerModel payloadModel = messagePayloadContainerMapping.toModel(payload, new MessagePayloadContainerModel());
            payloadModel.setMessage(model);
            model.getPayloads().add(payloadModel);
        }

        return model;
    }

    @Override
    public Message mapToEntity(MessageModel model, Message entity) {
        entity.setId(model.getId());
        entity.setSender(model.getSender());
        entity.setRecipient(model.getRecipient());
        entity.setTimestamp(model.getTimestamp());
        entity.setDirection(model.getDirection());

        List<PayloadContainer> payloadContainers = new ArrayList<>(entity.getMessagePayloads().size());
        for (MessagePayloadContainerModel containerModel : model.getPayloads()) {
            payloadContainers.add(messagePayloadContainerMapping.toEntity(containerModel));
        }
        entity.setMessagePayloads(payloadContainers);
        return entity;
    }
}
