package org.gcube.application.geoportal.db;

import static org.junit.Assert.assertEquals;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.gcube.application.geoportal.TestModel;
import org.gcube.application.geoportal.managers.AbstractRecordManager;
import org.gcube.application.geoportal.managers.ConcessioneManager;
import org.gcube.application.geoportal.managers.EMFProvider;
import org.gcube.application.geoportal.managers.ManagerFactory;
import org.gcube.application.geoportal.model.concessioni.Concessione;
import org.gcube.application.geoportal.model.db.DBConstants;
import org.gcube.application.geoportal.model.fault.PersistenceException;
import org.gcube.application.geoportal.model.fault.PublishException;
import org.gcube.application.geoportal.model.fault.ValidationException;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.model.report.ValidationReport.ValidationStatus;
import org.gcube.application.geoportal.utils.Serialization;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Records {

	@AfterClass
	public static void shutdown() {
		AbstractRecordManager.shutdown();
		
	}
	@BeforeClass
	public static void init() {
		AbstractRecordManager.setDefaultProvider(new EMFProvider() {
			
			@Override
			public EntityManagerFactory getFactory() {
				try{
					return Persistence.createEntityManagerFactory(DBConstants.INTERNAL.DB_NAME);
				}catch(Throwable t1) {					
					throw new RuntimeException("Unable to init local databse",t1);
				}
			}
			
			@Override
			public void shutdown() {
				
			}
		});	}
	
	@Test
	public void Concessioni() throws PersistenceException, ValidationException, PublishException, JsonProcessingException {
		Concessione conc=TestModel.prepareConcessione();
		System.out.println("Record is "+conc);
		ValidationReport report=conc.validate();
		
		System.out.println("Validation report is : "+Serialization.prettyPrint(report));
		Assert.assertEquals(report.getStatus(), ValidationStatus.PASSED);
		
		
		
		
		ConcessioneManager manager=ManagerFactory.registerNew(conc);
		String updatedString="Definitely a new name for this thing";
		conc.setNome(updatedString);
		
		manager.commit(false);
		Concessione registered=manager.getRecord();
		assertEquals(updatedString, registered.getNome());
		Assert.assertNotNull(registered);
		Assert.assertNotNull(registered.getId());
		
		System.out.println("Registered bean :"+registered);
		
		
		Concessione loaded=(Concessione) ManagerFactory.getByRecordID(registered.getId()).getRecord();
		System.out.println("Loaded bean : "+loaded);
		Assert.assertEquals(loaded, registered);
	}

	
}
