package org.mercury_im.messenger.data.mapping;

import org.mercury_im.messenger.data.model.MessagePayloadModel;
import org.mercury_im.messenger.data.model.MessagePayloadContainerModel;
import org.mercury_im.messenger.entity.message.PayloadContainer;
import org.mercury_im.messenger.entity.message.content.Payload;

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

import javax.inject.Inject;

public class MessagePayloadContainerMapping extends AbstractMapping<PayloadContainer, MessagePayloadContainerModel> {

    private final MessagePayloadMapping messagePayloadMapping;

    @Inject
    public MessagePayloadContainerMapping(MessagePayloadMapping messagePayloadMapping) {
        this.messagePayloadMapping = messagePayloadMapping;
    }

    @Override
    public PayloadContainer newEntity(MessagePayloadContainerModel model) {
        return new PayloadContainer();
    }

    @Override
    public MessagePayloadContainerModel newModel(PayloadContainer entity) {
        return new MessagePayloadContainerModel();
    }

    @Override
    public MessagePayloadContainerModel mapToModel(PayloadContainer entity, MessagePayloadContainerModel model) {
        model.getContents().clear();
        for (Payload contentEntity : entity.getMessageContents()) {
            MessagePayloadModel contentModel = messagePayloadMapping.toModel(contentEntity, new MessagePayloadModel());
            contentModel.setPayloadContainer(model);
            model.getContents().add(contentModel);
        }

        return model;
    }

    @Override
    public PayloadContainer mapToEntity(MessagePayloadContainerModel model, PayloadContainer entity) {
        entity.setId(model.getId());

        List<Payload> contents = new ArrayList<>(model.getContents().size());
        for (MessagePayloadModel contentModel : model.getContents()) {
            Payload contentEntity = messagePayloadMapping.toEntity(contentModel, null);
            contents.add(contentEntity);
        }
        entity.setMessageContents(contents);

        return entity;
    }
}
