package com.braintree.graphql.commands.impl;

import com.braintree.commands.impl.AbstractCommand;
import com.braintree.graphql.commands.BrainTreeGraphQLExchangeLegacyIdCommand;
import com.braintree.hybris.data.graphql.commands.request.BrainTreeExchangeLegacyIdRequest;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.braintree.constants.BraintreeConstants.ID_FROM_LEGACY_PARAMETER;
import static com.braintree.constants.BraintreeConstants.LEGACY_ID_PARAMETER;
import static com.braintree.constants.BraintreeConstants.RESULT_DATA;
import static com.braintree.constants.BraintreeConstants.RESULT_ERRORS;
import static com.braintree.constants.BraintreeConstants.TYPE_PARAMETER;

/**
 * This class extends AbstractCommand, implements BrainTreeGraphQLExchangeLegacyIdCommand and is used in GraphQL API.
 */
public class DefaultBrainTreeGraphQLExchangeLegacyIdCommand extends
        AbstractCommand<BrainTreeExchangeLegacyIdRequest, String>
        implements BrainTreeGraphQLExchangeLegacyIdCommand {

    private static final Logger LOG = Logger.getLogger(DefaultBrainTreeGraphQLExchangeLegacyIdCommand.class);

    private static final String DEFINITION_FILE_NAME = "idFromLegacyId";
    private static final String BT_EXCHANGE_LEGACY_ID_ERROR_DUE_TO_EXCHANGING_TOKEN_MESSAGE =
            "[BT Exchange legacy id] Error due to exchanging token. ";
    private static final String CAN_NOT_FIND_GRAPH_QL_QUERY_DEFINITION_FILE_MESSAGE = "[BT Exchange legacy id] can not find graphQL query definition file";

    @Override
    public String perform(BrainTreeExchangeLegacyIdRequest request) {
        try {
            Map<String, Object> result = makeGraphQlCall(DEFINITION_FILE_NAME, createVariablesMap(request));
            Map<String, Object> data = (Map<String, Object>) result.get(RESULT_DATA);
            List<Map<String, Object>> errors = (List<Map<String, Object>>) result.get(RESULT_ERRORS);

            if (errors != null) {
                String errorMessage =
                        BT_EXCHANGE_LEGACY_ID_ERROR_DUE_TO_EXCHANGING_TOKEN_MESSAGE + getFistErrorMessage(errors);
                LOG.error(errorMessage);
                throw new IllegalArgumentException(errorMessage);
            }

            return (String) data.get(ID_FROM_LEGACY_PARAMETER);
        } catch (IOException e) {
            LOG.error(CAN_NOT_FIND_GRAPH_QL_QUERY_DEFINITION_FILE_MESSAGE, e);
            throw new IllegalArgumentException(e);
        }

    }

    private Map<String, Object> createVariablesMap(BrainTreeExchangeLegacyIdRequest brainTreeExchangeLegacyIdRequest) {
        Map<String, Object> map = new HashMap<>();
        map.put(LEGACY_ID_PARAMETER, brainTreeExchangeLegacyIdRequest.getLegacyId());
        map.put(TYPE_PARAMETER, brainTreeExchangeLegacyIdRequest.getType());
        return map;
    }

}
