package meerkat.bulletinboard.sqlserver.mappers;

import com.google.protobuf.InvalidProtocolBufferException;
import meerkat.protobuf.BulletinBoardApi.UnsignedBulletinBoardMessage;
import meerkat.protobuf.BulletinBoardApi.BulletinBoardMessage;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Arbel Deutsch Peled on 11-Dec-15.
 */
public class MessageMapper implements RowMapper<BulletinBoardMessage.Builder> {

    @Override
    public BulletinBoardMessage.Builder mapRow(ResultSet rs, int rowNum) throws SQLException {

        BulletinBoardMessage.Builder builder = BulletinBoardMessage.newBuilder();

        try {
            builder.setEntryNum(rs.getLong(1))
                    .setMsg(UnsignedBulletinBoardMessage.parseFrom(rs.getBytes(2)));

        } catch (InvalidProtocolBufferException e) {
            throw new SQLException(e.getMessage(), e);
        }

        return builder;
    }

}
