package org.gcube.application.geoportal.clients.serialization;

import org.gcube.application.cms.tests.TestProfiles;
import org.gcube.application.geoportal.client.utils.Serialization;
import org.gcube.application.geoportal.common.model.JSONPathWrapper;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.Field;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.HandlerDeclaration;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.utils.Files;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;

public class UseCaseDescriptors {

    private static UseCaseDescriptor readProfile(String file) throws IOException {
        return Serialization.read(getJSON(file), UseCaseDescriptor.class);
    }

    private static String getJSON(String file) throws IOException {
        return Files.readFileAsString(
                new File(TestProfiles.BASE_FOLDER,file).getAbsolutePath(), Charset.defaultCharset());
    }

    @Test
    public void read () throws IOException {
        for (Map.Entry<String, UseCaseDescriptor> entry : TestProfiles.profiles.entrySet()) {
            String s = entry.getKey();
            UseCaseDescriptor useCaseDescriptor = entry.getValue();
            System.out.println("Checking " + s);

            validate(useCaseDescriptor);
            System.out.println(useCaseDescriptor);
            UseCaseDescriptor converted = Serialization.convert(useCaseDescriptor, UseCaseDescriptor.class);
            assertEquals(useCaseDescriptor, converted);
            JSONPathWrapper wrapper = new JSONPathWrapper(Serialization.asDocument(useCaseDescriptor).toJson());
            List<List> foundObjects = wrapper.getByPath("$." + UseCaseDescriptor.HANDLERS, List.class);

            foundObjects.get(0).forEach(o -> {
                HandlerDeclaration h = Serialization.convert(o, HandlerDeclaration.class);
                System.out.println(h);
                validate(h);
            });
        }

    }


    private void validate(UseCaseDescriptor useCaseDescriptor){
        assertTrue(useCaseDescriptor.getId()!=null);
        if(useCaseDescriptor.getHandlers()!=null)
            useCaseDescriptor.getHandlers().forEach(handlerDeclaration -> validate(handlerDeclaration));
        if(useCaseDescriptor.getSchema()!=null)
            validate(useCaseDescriptor.getSchema());

    }
    private void validate(HandlerDeclaration handler){
        assertTrue(handler.getId()!=null);
    }

    private void validate(Field f){
        //assertTrue(f.getType()!=null);

    }
}
