package org.gcube.application.cms.usecases;

import org.gcube.application.cms.tests.TokenSetter;
import org.gcube.application.geoportal.client.legacy.ConcessioniManagerI;
import org.gcube.application.geoportal.common.model.legacy.Concessione;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLong;

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

public class RepublishAll {

    public static void main(String[] args) throws Exception {
        TokenSetter.set("/gcube/devsec/devVRE");

        ConcessioniManagerI manager=statefulMongoConcessioni().build();


        ArrayList<String> toSkipIds=new ArrayList<>();


        AtomicLong count=new AtomicLong(0);
        AtomicLong nullCount=new AtomicLong(0);
        AtomicLong errCount=new AtomicLong(0);
        Iterator<Concessione> it=null;
//        it=manager.getList();
        it=manager.search("{\"report.status\" :  {$eq : \"WARNING\"}}");

        it.forEachRemaining((Concessione c)->{
            try{
                String currentId=c.getMongo_id();
                if(currentId==null) {
                    System.out.println("ID IS NULL " + c);
                    nullCount.incrementAndGet();
                }
                else
                if(toSkipIds.contains(currentId))
                    System.out.println("Skipping "+currentId);
                else {
                    System.out.println("Upublishing " + c.getMongo_id());
                    manager.unPublish(c.getMongo_id());

                    System.out.println("Republishing" + c.getMongo_id());
                    manager.publish(c.getMongo_id());
                }
            }catch(Throwable throwable){
                System.err.println(throwable);
                errCount.incrementAndGet();
            }finally {
                count.incrementAndGet();
            }
        });

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

    }
}
