package ua.ansymo.hintco

import be.uantwerpen.cosys.contractLang.ContractLangPackage
import be.uantwerpen.cosys.contractLang.Root
import java.util.HashMap
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.EPackage
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl
import ua.ansymo.hintco.HintConfiguration

class ModelStorage {
	// See https://stackoverflow.com/questions/12458852/load-emf-model-instance-in-xtend
	
	def storeCandidates(String uri, HintConfiguration c){
		val rs = new ResourceSetImpl().createResource(URI.createURI(uri))
		rs.contents.add(c)
		rs.save(new HashMap)
	}
	
	def loadCandidates(String uri){
		doEMFSetup()
		val resourceSet = new ResourceSetImpl
		val res = resourceSet.getResource(URI.createURI(uri), true)
		val candidates = res.contents.get(0) as HintConfiguration
		
		ModelValidation.validate(candidates)
		
		return candidates
	}
	
	def loadContractSet(String uri){
		doContractEMFSetup()
		val resourceSet = new ResourceSetImpl
		val res = resourceSet.getResource(URI.createURI(uri), true)
		val contractSet = (res.contents.get(0) as Root).contractSet
		return contractSet
	}
	
	def doContractEMFSetup() {
		val reg = EPackage.Registry.INSTANCE
		if (!reg.containsKey(ContractLangPackage.eNS_URI)) {
			reg.put(ContractLangPackage.eNS_URI, ContractLangPackage.eINSTANCE);
		}
	}
	
	def doEMFSetup(){
		Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("xmi", new XMIResourceFactoryImpl);
		Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put(HintcoPackage.eNAME, new XMIResourceFactoryImpl);
		// Forces initialization of the package.
		// See https://www.eclipse.org/forums/index.php?t=msg&th=274972&goto=777450&#msg_777450
		HintcoPackage.eINSTANCE
	}
	
}
