package org.gcube.application.cms.usecases;

import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.gcube.application.cms.tests.TokenSetter;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.rest.QueryRequest;
import org.gcube.application.geoportal.common.model.rest.StepExecutionRequest;
import org.gcube.application.geoportal.common.rest.Projects;
import org.gcube.application.geoportal.common.utils.tests.GCubeTest;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicLong;

import static org.gcube.application.geoportal.client.plugins.GeoportalAbstractPlugin.projects;

@Slf4j
public class PublishSubmitted {

    public static void main(String[] args) throws RemoteException {
        TokenSetter.set(GCubeTest.getContext());
        Projects<Project> client=projects("profiledConcessioni").build();

        QueryRequest query = new QueryRequest();
        query.setFilter(Document.parse("{\"_lifecycleInformation._lastOperationStatus\":{\"$eq\":\"OK\"},\"_lifecycleInformation._phase\":{\"$eq\":\"Pending Approval\"}}"));

        AtomicLong count=new AtomicLong();
        final StepExecutionRequest step = new StepExecutionRequest();
        step.setStepID("APPROVE-SUBMITTED");

        HashMap<String,String> errors = new HashMap<>();

        client.query(query).forEachRemaining(project -> {
            try{
                   log.info("Publishing N {}, ID {} ",count.incrementAndGet(),project.getId());
                   client.performStep(project.getId(), step);
            }catch(Throwable t){
                t.printStackTrace(System.err);
                errors.put(project.getId(),t.getMessage());
            }
        });

        System.out.println("Performed OP on "+count.get()+" projects.");
        System.out.println("Errors count : "+errors.size());
        errors.forEach((k,v) -> System.err.println(k+"\t"+v));
    }

}
