package org.gcube.application.cms.usecases.legacyConcessioni;

import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.geoportal.common.model.legacy.Concessione;
import org.gcube.application.geoportal.common.utils.Files;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

public class ClusterizeImportFolder {


    public static void main(String[] args) throws IOException {
        final File dir=new File("/Users/fabioisti/git/gcube-cms-suite/import1668778302348");


        ConcessioniManagementUtils.ImportFolder folder=ConcessioniManagementUtils.loadImportFolder(dir);
        folder.sort();

        int clusterSize = 50;

        int clusterNum=1;
        File destDir =null;

        for (Map.Entry<String, ArrayList<Concessione>> entry : folder.getRelationshipMap().entrySet()) {
            String s = entry.getKey();
            ArrayList<Concessione> l = entry.getValue();
            if(destDir==null||destDir.list().length+l.size()>=clusterSize){
                destDir = new File(dir, "cluster_" + clusterNum);
                destDir.mkdirs();
                clusterNum++;
            }
            File finalDestDir = destDir;
            l.forEach(c -> {
                try {
                    Files.saveString(Serialization.write(c),new File(finalDestDir,c.getMongo_id()+".json").toPath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }

        System.out.println("Created "+clusterNum--+" sub folders");

    }

}
