package meerkat.bulletinboard.sqlserver.mappers;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import meerkat.bulletinboard.sqlserver.BulletinBoardSQLServer.SQLQueryProvider.QueryType;
import meerkat.comm.MessageOutputStream;
import meerkat.protobuf.BulletinBoardApi.BulletinBoardMessage;
import meerkat.protobuf.BulletinBoardApi.UnsignedBulletinBoardMessage;
import meerkat.protobuf.Crypto;
import meerkat.util.BulletinBoardUtils;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Arbel Deutsch Peled on 21-Feb-16.
 */
public class MessageStubCallbackHandler implements RowCallbackHandler {

    private final MessageOutputStream<BulletinBoardMessage> out;

    public MessageStubCallbackHandler(MessageOutputStream<BulletinBoardMessage> out) {

        this.out = out;

    }

    @Override
    public void processRow(ResultSet rs) throws SQLException {

        BulletinBoardMessage result;

        result = BulletinBoardMessage.newBuilder()
                .setEntryNum(rs.getLong(1))
                .setMsg(UnsignedBulletinBoardMessage.newBuilder()
                        .setData(ByteString.copyFrom(rs.getBytes(2)))
                        .setTimestamp(BulletinBoardUtils.toTimestampProto(rs.getTimestamp(3)))
                        .build())
                .build();

        try {

            out.writeMessage(result);

        } catch (IOException e) {

            //TODO: log
            e.printStackTrace();

        }

    }

}
