package com.urbancode.urelease.integration.xldeploy.sync

import com.urbancode.release.rest.framework.ClientIntegrated
import com.urbancode.release.rest.framework.QueryParams.FilterClass
import com.urbancode.commons.util.query.QueryFilter.FilterType
import com.google.common.collect.Lists

class FullSyncClient <T extends ClientIntegrated<T>> extends SyncClient<T> {
    List<T> deleteList
    String providerId

    public FullSyncClient(T syncObject, int syncMax, String providerId) {
        super(syncObject, syncMax)
        this.removalCount = 0
        this.providerId = providerId
    }

    @Override
    public void addImport(T newImport) {
        importList.add(newImport)

        if (importList.size() >= syncMax) {
            syncImports()
        }

        /* If this is the first import being added, initialize the deleteList */
        if (deleteList == null) {
            deleteList = syncObject.filter("integrationProvider.id",
                FilterClass.UUID, FilterType.EQUALS, providerId).when().getAll()
        }

        for (T delete : deleteList) {
            if (delete.externalId.equals(newImport.externalId)) {
                /* The import still exists in XL Deploy, so don't remove it from UCR */
                deleteList.remove(delete)
                break
            }
        }
    }

    @Override
    public void syncImports() {
        if (importList.size() > 0) {
            List<T> imported = syncObject.sync(importList)
            importList.clear()
            importCount += imported.size()
        }
    }

    @Override
    public void syncRemovals() {
        if (deleteList?.size() > 0) {
            List<List<T>> partitionedLists = Lists.partition(deleteList, syncMax)
            for (List<T> list : partitionedLists) {
                syncObject.delete(list)
                removalCount += list.size()
            }
        }
    }
}
