package com.atlassian.bitbucket.mesh.transaction;

import com.atlassian.bitbucket.mesh.git.exception.CommandFailedException;
import com.atlassian.bitbucket.mesh.process.handler.StringStdioHandler;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcSetMetadataRequest;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcTransaction;

import java.util.Map;

public class TransactSetMetadataTest extends AbstractPreparedActionWriteTest {

    @Override
    protected RpcTransaction.Builder createTransaction(RpcTransaction.Builder builder) {
        return builder.setSetMetadata(RpcSetMetadataRequest.newBuilder()
                .putMetadata("foo", "bar")
                .setRepository(repository.getId()));
    }

    @Override
    protected RpcTransaction.Builder createTransactionThatTriggersError(RpcTransaction.Builder builder) {
        return builder.setSetMetadata(RpcSetMetadataRequest.newBuilder()
                .putMetadata("foo", "bar")
                .setRepository("no-such-repository"));
    }

    @Override
    protected boolean isApplied(RpcTransaction transaction) {
        Map<String, String> expected = transaction.getSetMetadata().getMetadataMap();
        return expected.entrySet().stream().allMatch(entry -> {
            try {
                String value = builderFactory.builder(repository).config()
                        .get("bitbucket." + entry.getKey())
                        .build(new StringStdioHandler())
                        .run();
                return entry.getValue().equals(value);
            } catch (CommandFailedException e) {
                //git config returns exit code 1 if the requested config name is not found
                return false;
            }
        });
    }
}
