package org.gcube.application.cms.usecases;

import lombok.extern.slf4j.Slf4j;
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.rest.Projects;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

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

@Slf4j
public class ClearProjects {

    public static void main(String[] args) throws RemoteException, InterruptedException {
        String context="/gcube/devsec/devVRE";

        //String context="/pred4s/preprod/preVRE";

        TokenSetter.set(context);

        Projects<Project> client=projects("profiledConcessioni").build();;


        ArrayList<String> toSkipIds=new ArrayList<>();
//        toSkipIds.add("6102c8dd02ad3d05b5f81df4");
//        toSkipIds.add("610415af02ad3d05b5f81ee3");

        AtomicLong count=new AtomicLong(0);
        AtomicLong nullCount=new AtomicLong(0);

        ConcurrentSkipListSet<String> errors = new ConcurrentSkipListSet<>();

        AtomicLong found=new AtomicLong(0);

        Iterator<Project> it=null;
        it=client.query(new QueryRequest());
//        it=manager.search("{\"nome\" : {$regex : \"Mock .*\"}, \"creationTime\" :{$gt : \"2021-10-18T13:58:53.326\"}}");

        ExecutorService service = Executors.newFixedThreadPool(1);

        ConcurrentSkipListSet<String> ids = new ConcurrentSkipListSet<>();

   //    it.forEachRemaining(project -> ids.add(project.getId()));






        it.forEachRemaining((Project c)->{
            System.out.println("Found ID "+c.getId()+" N° "+found.incrementAndGet());

            service.submit(new Runnable() {
                @Override
                public void run() {
                    try{
                        TokenSetter.set(context);
                        String currentId=c.getId();
                        if(currentId==null) {
                            System.out.println("ID IS NULL " + c);
                            nullCount.incrementAndGet();
                        }
                        if(c.getLock()!=null){
                            System.out.println("Unlocking "+currentId);
                            client.forceUnlock(currentId);
                        }

                        else
                        if(toSkipIds.contains(currentId))
                            System.out.println("Skipping "+currentId);
                        else {
                            System.out.println("Deleting " + c.getId());
                            client.deleteById(c.getId(),true);
                        }
                    }catch(Throwable throwable){
                        System.err.println(throwable);
                        errors.add(c.getId());
                       // try {Thread.sleep(1000);} catch (InterruptedException i) {}
                    }finally{
                        System.out.println("Handled N "+count.incrementAndGet()+" concessioni");
                    }
                }
            });
        });

        while (!service.awaitTermination(1, TimeUnit.MINUTES)) {
            log.info("Waiting .. completed {}, out of {} ",count.get(),found.get());
            if(found.get()==count.get()) service.shutdown();
        }

        System.out.println("Done "+count.get()+" [null : "+nullCount.get()+", err : "+errors.size()+"]");

        System.out.println("Errors : ");
        errors.forEach(s -> System.out.println(s));

    }
}
