package com.braintree.replenishment.dao.impl;

import com.braintree.model.BrainTreePaymentInfoModel;
import com.braintree.replenishment.dao.BraintreeCartToOrderCronJobDao;
import de.hybris.platform.orderscheduling.model.CartToOrderCronJobModel;
import de.hybris.platform.servicelayer.internal.dao.AbstractItemDao;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.SearchResult;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DefaultBraintreeCartToOrderCronJobDao extends AbstractItemDao implements BraintreeCartToOrderCronJobDao {

    protected static final String GET_CRON_JOB_BY_PAYMENT_METHOD_TOKEN =
            "SELECT {cronJob:" + CartToOrderCronJobModel.PK + "} FROM {"
                    + CartToOrderCronJobModel._TYPECODE + " as cronJob JOIN " + BrainTreePaymentInfoModel._TYPECODE +
                    " as brainTreePaymentInfo" + " ON {cronJob:" + CartToOrderCronJobModel.PAYMENTINFO
                    + "} = {brainTreePaymentInfo:" +
                    BrainTreePaymentInfoModel.PK + "}} " + "WHERE {brainTreePaymentInfo:" +
                    BrainTreePaymentInfoModel.PAYMENTMETHODTOKEN + "} = ?paymentMethodToken" +
                    " AND {brainTreePaymentInfo:" + BrainTreePaymentInfoModel.DUPLICATE + "} = ?duplicate";

    @Override
    public List<CartToOrderCronJobModel> findCronJobsByPaymentMethodToken(String paymentMethodToken) {
        final Map<String, Object> params = new HashMap<String, Object>();
        params.put("paymentMethodToken", paymentMethodToken);
        params.put("duplicate", Boolean.FALSE);
        final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(GET_CRON_JOB_BY_PAYMENT_METHOD_TOKEN);
        flexibleSearchQuery.addQueryParameters(params);
        flexibleSearchQuery.setResultClassList(Collections.singletonList(CartToOrderCronJobModel.class));
        final SearchResult<CartToOrderCronJobModel> searchResult = search(flexibleSearchQuery);
        return searchResult.getResult();
    }
}
