package eu.blogforever.mfextractor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

import org.xml.sax.SAXException;

public class Extract {
	
	public static void main(String[] args) 
			throws SAXException, IOException{
		
		
		ExtractionInput input = new ExtractionInput();
		MicroformatExtractor extractor = new MicroformatExtractor();
		
		String output_format = null;	// Output format
		String output_file = null;      // Output file
		String documentURI = null;
		
		try {
			
			if(args.length<1){
				printUsage();
			 	return;
			}
			for (int i = 0; i < args.length; i++) {
				if("-h".equals(args[i])){
						printUsage();
						return;
				} else if("-uri".equals(args[i])){
					documentURI = args[++i];
				}
				else if ("-f".equals(args[i])) {
				
					output_format = args[++i];
					if(output_format.equals("rdfxml") && output_format.equals("ntriples") && output_format.equals("turtle")){
			        	System.out.println("Invalid output format. Use default format.");
			        }
				}
				else if ("-o".equals(args[i])) {
					output_file = args[++i];
				}
			}

			if (args[0].startsWith("http://")){
				URL url = new URL(args[0]);
				input.setInput(url);
			}
			else{
				if(documentURI==null){
					System.out.println("Document URI must be specified");
					printUsage();
					return;
				}
				File inout_file = new File(args[0]);
				input.setInput(inout_file, documentURI);
			}
			
			OutputStream out = null;
			if(output_file == null)
				out = System.out;
			else
				out = new FileOutputStream(output_file);			
		     
			
			
			if(output_format==null)
				extractor.extractToRDFXML(input, out);	
			else if(output_format.equals("rdfxml"))
				extractor.extractToRDFXML(input, out);
			else if(output_format.equals("ntriples"))
				extractor.extractToNTriples(input, out);
			else if(output_format.equals("turtle"))
				extractor.extractToTurtle(input, out);
			
			
		} catch (Exception e) {
			System.out.println("Exception: " + e.getMessage());
			e.printStackTrace();
		}
	     
	}
	  
	public static void printUsage(){
		System.out.println
	      ("Usage: Extract <url> | <filepath -uri documentURI> [-o output-file [-f output-format]]\n" +
	    		"Input can be a filepath or a url. If it's a path, document's URI must be specified.\n" +
	      		"Usage examples: \n" +
	      		"      Extract http://www.example.com -o /path/to/output/file\n" +
	      		"      Extract /path/to/input/file -uri http://example.com -o path/to/output/file\n");
		System.out.println(
				"Arguments\n" +
				"	-f <output-format>" + "\tChoose one of rdfxml [default], ntriples, turtle\n" +
				"	-o <output-file>  " + "\tIf not exist the program writes to stdout\n" + 
				"	-h	\t\tPrint this help"
				);
		
	}
	
}
