package com.braintree.transaction.dao.impl;

import com.braintree.enums.BraintreePaymentTransactionStatus;
import com.braintree.transaction.dao.BraintreeTransactionDAO;
import de.hybris.platform.core.servicelayer.data.SearchPageData;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.servicelayer.internal.dao.AbstractItemDao;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.paginated.PaginatedFlexibleSearchParameter;
import de.hybris.platform.servicelayer.search.paginated.PaginatedFlexibleSearchService;
import de.hybris.platform.servicelayer.util.ServicesUtil;

import java.util.List;

public class DefaultBraintreeTransactionDAO extends AbstractItemDao implements BraintreeTransactionDAO {

    private static final String GET_PAYMENT_TRANSACTION_BY_PAYMENT_TRANSACTION_STATUSES = "select {"
            + PaymentTransactionModel.PK + "} from {" + PaymentTransactionModel._TYPECODE + "} where {"
            + PaymentTransactionModel.BRAINTREEPAYMENTTRANSACTIONSTATUS + "} in (?transactionStatuses)";

    private static final String GET_TRANSACTION_BY_TRANSACTION_ID = "select {" + PaymentTransactionModel.PK
            + "} FROM {" + PaymentTransactionModel._TYPECODE + "} where {" +
            PaymentTransactionModel.REQUESTID + "} = ?transactionId";

    private static final String TRANSACTION_ID = "transactionId";

    private PaginatedFlexibleSearchService paginatedFlexibleSearchService;

    @Override
    public SearchPageData<PaymentTransactionModel> getPaymentTransactionsByStatuses(
            List<BraintreePaymentTransactionStatus> statuses, SearchPageData<PaymentTransactionModel> searchPage) {
        FlexibleSearchQuery query = new FlexibleSearchQuery(GET_PAYMENT_TRANSACTION_BY_PAYMENT_TRANSACTION_STATUSES);
        query.addQueryParameter("transactionStatuses", statuses);
        PaginatedFlexibleSearchParameter paginatedFlexibleSearchParameter = new PaginatedFlexibleSearchParameter();
        paginatedFlexibleSearchParameter.setFlexibleSearchQuery(query);
        paginatedFlexibleSearchParameter.setSearchPageData(searchPage);
        return paginatedFlexibleSearchService.search(paginatedFlexibleSearchParameter);
    }

    @Override
    public PaymentTransactionModel findTransactionByTransactionId(String transactionId) {
        ServicesUtil.validateParameterNotNull(transactionId, "transactionId cannot be null");

        FlexibleSearchQuery query = new FlexibleSearchQuery(GET_TRANSACTION_BY_TRANSACTION_ID);
        query.addQueryParameter(TRANSACTION_ID, transactionId);

        return getFlexibleSearchService().searchUnique(query);
    }

    public void setPaginatedFlexibleSearchService(PaginatedFlexibleSearchService paginatedFlexibleSearchService) {
        this.paginatedFlexibleSearchService = paginatedFlexibleSearchService;
    }
}
