package org.gcube.application.geoportal.service.engine.providers;

import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.cms.tests.TokenSetter;
import org.gcube.application.cms.tests.model.BasicTests;
import org.gcube.application.geoportal.common.model.legacy.Concessione;
import org.gcube.application.geoportal.common.model.rest.ConfigurationException;
import org.gcube.application.geoportal.common.utils.tests.GCubeTest;
import org.gcube.application.geoportal.service.model.internal.db.Mongo;
import org.junit.Test;

import java.util.function.Consumer;

import static com.mongodb.client.model.Filters.eq;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assume.assumeTrue;

public class MongoProviderTest extends BasicTests {

    @Test
    public void getConfiguration() throws ConfigurationException {
        assumeTrue(GCubeTest.isTestInfrastructureEnabled());
        TokenSetter.set(GCubeTest.getContext());
        MongoClientProvider provider = new MongoClientProvider();
        Mongo m = provider.getObject();
        System.out.println(m);
        assertNotNull(m);
    }

    public void performManualUpdate() throws ConfigurationException {
        assumeTrue(GCubeTest.isTestInfrastructureEnabled());
        TokenSetter.set(GCubeTest.getContext());
        MongoClientProvider provider = new MongoClientProvider();
        Mongo m = provider.getObject();
        MongoCollection c = m.getTheClient().getDatabase(m.getConnection().getDatabase()).
                getCollection("legacyConcessioni");


        c.find(eq("centroidLat",null))
                .forEach((Consumer) doc ->{
                    try{
                        Concessione record = Serialization.convert(doc, Concessione.class);
                        record.setCentroidLat((record.getPosizionamentoScavo().getBbox().getMaxLat()+
                                record.getPosizionamentoScavo().getBbox().getMinLat())/2);
                        record.setCentroidLong((record.getPosizionamentoScavo().getBbox().getMaxLong()+
                                record.getPosizionamentoScavo().getBbox().getMinLong())/2);

                        Document toSet = Document.parse(Serialization.write(record));
                        toSet.put("_id",new ObjectId(record.getMongo_id()));

                        c.findOneAndUpdate(eq("_id",toSet.get("_id")),toSet);
                        System.out.println("Updated "+record.getMongo_id()+" : "+record.getNome());
                    }catch (Throwable e){
                        e.printStackTrace(System.err);
                    }
                });

    }

}
