/**
 * 
 */
package ISClient;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.gcube.common.core.contexts.GHNContext;
import org.gcube.common.core.informationsystem.publisher.ISPublisher;
import org.gcube.common.core.resources.GCUBEGenericResource;
import org.gcube.common.core.scope.GCUBEScope;
import org.gcube.common.core.security.GCUBESecurityManagerImpl;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * @author Spyros Boutsis, NKUA
 *
 */
public class PublishGenericResource {
	
	public static void main(String[] args) {
		
		if (args.length < 2) {
			System.out.println("Wrong number of arguments. Usage:");
			System.out.println("PublishTP <scope> <GR_File_Name1> [ <GR_File_Name2> ... ]");
			System.exit(-1);
		}
		
		try {
			GCUBESecurityManagerImpl managerSec = new GCUBESecurityManagerImpl() {  public boolean isSecurityEnabled() {return false;}};
			
			GCUBEScope scope = GCUBEScope.getScope(args[0]);
			ISPublisher publisher = GHNContext.getImplementation(ISPublisher.class);

			for (int i=1; i< args.length; i++) {
				FileReader fis = new FileReader(args[i]);
				GCUBEGenericResource resource = GHNContext.getImplementation(GCUBEGenericResource.class);
				resource.load(fis);
				resource.setID("");
				
				String gr = publisher.registerGCUBEResource(resource, scope, managerSec);
				//System.out.println(gr);

				resource.load(new StringReader(gr));
				System.out.println(args[i] + ": generic resource uploaded, ID = " + resource.getID());
				
				FileOutputStream os = new FileOutputStream(args[i]);
				serialize(parseXMLString(gr), os);
				os.close();
				System.out.println(args[i] + ": Profile updated in file");
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		
	public static void serialize(Document doc, OutputStream out) throws Exception {
        OutputFormat format = new OutputFormat(doc);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(doc);
    }
	
	public static Document parseXMLString(String XMLdoc) throws ParserConfigurationException, SAXException, IOException  {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbFactory.newDocumentBuilder();
		return builder.parse(new InputSource(new StringReader(XMLdoc)));
	}
}
