import org.slf4j.Logger
import org.slf4j.LoggerFactory

import com.gridnine.xtrip.common.model.EntityContainer
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.Organization
import com.gridnine.xtrip.common.model.profile.OrganizationIndex
import com.gridnine.xtrip.common.search.SearchQuery
import com.gridnine.xtrip.common.search.SortOrder

Logger logger = LoggerFactory.getLogger('groovy-script')

logger.info("CIR: organization started")

int countt = 0
int amount = 10000

int processed = 0
int found = 0

try {

    while(true) {

        int limit = amount
        int offset = countt * amount

        logger.info("CIR: searching " + limit + " starting from " + offset)

        SearchQuery query = new SearchQuery()

        query.setLimit(limit)
        query.setOffset(offset)

        query.getCriteria().orders.put("containerUid", SortOrder.ASC)

        query.getPreferredProperties().add("containerUid")

        List<OrganizationIndex> indexes = EntityStorage.get().search(OrganizationIndex.class, query).getData()

        logger.info("CIR: found " + indexes.size() + " profiles")

        if(indexes.size() == 0) {
            break
        }

        for(OrganizationIndex index : indexes) {

            logger.info("CIR: processing " + processed + " | " + found + " | " + index.getSource().getUid())

            EntityContainer<Organization> organizationContainer = EntityStorage.get().resolve(index.getSource())

            if(organizationContainer != null) {

                Organization organization = organizationContainer.getEntity()

                if(organization.getCards().size() > 0) {

                    logger.info("CIR: found card(s) " + index.getSource() + " (" + index.getSource().getUid() + ")")
                    
                    organizationContainer.getVersionInfo().setDataSource("cir-migration-2-1-task")
                    
                    EntityStorage.get().save(organizationContainer, false)

                    found++
                }
                
            } else {
                logger.info("CIR: unable to load " + index.getSource() + " (" + index.getSource().getUid() + ")")
            }

            processed++
        }

        countt++
    }
    
} catch(Throwable t) {
    logger.error('error occured', t)
}

logger.info("CIR: processed " + processed)
logger.info("CIR: found " + found)

logger.info("CIR: organization finished")
