/*
 Set up new property passwordForSingleAuthenticationActive for PayPal Customer.
 This property is used for indicate is customer should be able to setup password or not.
 */

package braintreeb2baddon.groovy
import de.hybris.platform.core.servicelayer.data.SearchPageData
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery
import de.hybris.platform.servicelayer.search.paginated.PaginatedFlexibleSearchParameter
import de.hybris.platform.core.model.user.CustomerModel
import de.hybris.platform.servicelayer.search.paginated.util.PaginatedSearchUtils
import org.apache.commons.lang.math.NumberUtils

modelService=spring.getBean("modelService");
flexibleSearchService = spring.getBean('flexibleSearchService')
paginatedFlexibleSearchService = spring.getBean('paginatedFlexibleSearchService')

COUNT_OF_CREATED_CUSTOMERS_QUERY =
        'SELECT count({c:pk}) FROM  {Customer as c }' +
                'WHERE {c:payPalPayerId} IS NOT NULL'
CREATED_CUSTOMERS_QUERY =
        'SELECT {c:pk} FROM  {Customer as c }' +
                'WHERE {c:payPalPayerId} IS NOT NULL'
pageSize = 1000



FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery(COUNT_OF_CREATED_CUSTOMERS_QUERY)
flexibleSearchQuery.setResultClassList(Arrays.asList(Integer.class))
int count = flexibleSearchService.searchUnique(flexibleSearchQuery)

int lastPage = getLastPage(count, pageSize)
for (int page = 0; page <= lastPage; page++) {
    List<CustomerModel> customers = searchCustomers(page)
    customers.each{
        it.passwordForSingleAuthenticationActive=false
        modelService.save(it)
    }

}

int getLastPage(int totalCountOfCustomers, int pageSize) {
    int lastPage = totalCountOfCustomers / pageSize
    if (totalCountOfCustomers % pageSize == 0) {
        lastPage -= NumberUtils.INTEGER_ONE
    }
    return lastPage;
}

List<CustomerModel> searchCustomers(int page) {
    SearchPageData searchPageData = PaginatedSearchUtils.createSearchPageDataWithPagination(pageSize, page, true)
    final PaginatedFlexibleSearchParameter parameter = new PaginatedFlexibleSearchParameter()
    parameter.setSearchPageData(searchPageData)
    final FlexibleSearchQuery flexibleQuery = new FlexibleSearchQuery(CREATED_CUSTOMERS_QUERY)
    parameter.setFlexibleSearchQuery(flexibleQuery)
    SearchPageData<CustomerModel> result = paginatedFlexibleSearchService.search(parameter)
    return result.getResults()
}
