package com.braintree.job;

import com.braintree.enums.BraintreePaymentTransactionStatus;
import com.braintree.model.BraintreeUpdatePaymentTransactionStatusCronJobModel;
import com.braintree.transaction.service.BrainTreeTransactionService;
import de.hybris.platform.core.servicelayer.data.PaginationData;
import de.hybris.platform.core.servicelayer.data.SearchPageData;
import de.hybris.platform.cronjob.enums.CronJobResult;
import de.hybris.platform.cronjob.enums.CronJobStatus;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.servicelayer.cronjob.AbstractJobPerformable;
import de.hybris.platform.servicelayer.cronjob.PerformResult;
import java.util.List;

public class BraintreeUpdatePaymentTransactionStatusJob extends AbstractJobPerformable<
        BraintreeUpdatePaymentTransactionStatusCronJobModel> {

    private BrainTreeTransactionService brainTreeTransactionService;
    private List<BraintreePaymentTransactionStatus> braintreePaymentTransactionStatuses;

    @Override
    public PerformResult perform(BraintreeUpdatePaymentTransactionStatusCronJobModel cronJobModel) {
        SearchPageData<PaymentTransactionModel> searchPageData = new SearchPageData<>();
        PaginationData paginationData = new PaginationData();
        paginationData.setCurrentPage(0);
        paginationData.setNeedsTotal(true);
        paginationData.setPageSize(cronJobModel.getPageSize());
        searchPageData.setPagination(paginationData);

        do {
            searchPageData = brainTreeTransactionService.getPaymentTransactionsByStatuses(
                    braintreePaymentTransactionStatuses, searchPageData);
            if (searchPageData.getResults() == null || searchPageData.getResults().isEmpty()) {
                break;
            }
            brainTreeTransactionService.updateBraintreePaymentTransactionStatuses(searchPageData.getResults());
            searchPageData.getPagination().setCurrentPage(searchPageData.getPagination().getCurrentPage() + 1);
        } while (Boolean.TRUE.equals(searchPageData.getPagination().getHasNext()));
        return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
    }

    public void setBrainTreeTransactionService(BrainTreeTransactionService brainTreeTransactionService) {
        this.brainTreeTransactionService = brainTreeTransactionService;
    }

    public void setBraintreePaymentTransactionStatuses(
            List<BraintreePaymentTransactionStatus> braintreePaymentTransactionStatuses) {
        this.braintreePaymentTransactionStatuses = braintreePaymentTransactionStatuses;
    }
}
