package com.braintree.job;

import com.braintree.configuration.service.BrainTreeConfigService;
import com.braintree.model.BrainTreePaymentInfoModel;
import com.braintree.model.ValidateExpiredCartsCronJobModel;
import com.braintree.payment.info.service.BraintreePaymentInfoService;
import de.hybris.platform.core.model.BraintreePluginConfigurationModel;
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.servicelayer.cronjob.AbstractJobPerformable;
import de.hybris.platform.servicelayer.cronjob.PerformResult;
import de.hybris.platform.store.BaseStoreModel;

import java.util.List;

public class ValidateExpiredCartsJobPerformable extends AbstractJobPerformable<ValidateExpiredCartsCronJobModel>{
    private BraintreePaymentInfoService braintreePaymentInfoService;

    @Override
    public PerformResult perform(ValidateExpiredCartsCronJobModel validateExpiredCartsCronJobModel) {
        SearchPageData<BrainTreePaymentInfoModel> searchPageData = new SearchPageData<>();

        PaginationData paginationData = new PaginationData();
        paginationData.setCurrentPage(0);
        paginationData.setNeedsTotal(true);
        paginationData.setPageSize(validateExpiredCartsCronJobModel.getPageSize());

        searchPageData.setPagination(paginationData);

        BraintreePluginConfigurationModel pluginConfiguration = validateExpiredCartsCronJobModel.getStore().getBraintreePluginConfiguration();

        do {
            searchPageData = braintreePaymentInfoService.getAllSavedCreditCard(searchPageData);
            braintreePaymentInfoService.updateAllExpiredStatuses(searchPageData.getResults(), pluginConfiguration);
            searchPageData.getPagination().setCurrentPage(searchPageData.getPagination().getCurrentPage() + 1);
        }while (searchPageData.getPagination().getHasNext());

        return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED);
    }

    public void setBraintreePaymentInfoService(BraintreePaymentInfoService braintreePaymentInfoService) {
        this.braintreePaymentInfoService = braintreePaymentInfoService;
    }
}
