package com.mycompany.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Iterator;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
 * ant task or command line utility, generates GI jss properties file 
 *  
 * @author bwalsh
 *
 */
public class Properties2Jss extends Task {

	
	/**
	 * convert 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			if ( args.length != 2 ) { 
				throw new Exception("usage path/to/messages.properties path/to/messages.jss") ;
			}
			Properties2Jss p2jss = new Properties2Jss() ;
			p2jss.setPropertiesFilePath( args[0] ) ;
			p2jss.setJssFilePath( args[1] ) ;
			p2jss.execute() ;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 	
	
	
	/**
	 *  source, where we read properties from.
	 */
	String propertiesFilePath = null ;

	/**
	 *  destination, where we write jss file.
	 */
	String jssFilePath = null ;

		
	/**
	 * 
	 */
	public void execute() throws BuildException {
		 Properties  properties = new Properties() ;
		 try {
			InputStream is = makeInputStream(propertiesFilePath) ;
			Writer writer = makeOutputWriter(jssFilePath) ;
			properties.load(is) ;
			if ( properties.size() == 0 ) {
				throw new Exception("No properties found in " + propertiesFilePath);
			}
			writer.write("<data jsxid=\"jsxroot\" jsxns=\"urn:tibco.com/v3.0/dynamicproperties/1\">\n");
			for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
				String key = (String) iter.next();
				String val = properties.getProperty(key) ;
				writer.write("    <record jsxid=\""+key+"\" jsxtext=\""+val+"\" type=\"jsxtext\"/>\n");
			}
			writer.write("</data>\n");
			writer.close();
		 } catch (Exception e) {
			throw new BuildException(e) ;
		} 
  }

   // ----------------------------------------------- private 
	private Writer makeOutputWriter(String path) throws IOException {
		BufferedWriter out = new BufferedWriter(new FileWriter(path)) ;		
		return out;
	}

 
	private FileInputStream makeInputStream(String path) throws FileNotFoundException {
		FileInputStream fileInputStream = new FileInputStream(new File(path));
		return fileInputStream;
	}


	// ---------------------------------------------- accessors
	public String getJssFilePath() {
		return jssFilePath;
	}
	

	public void setJssFilePath(String jssFilePath) {
		this.jssFilePath = jssFilePath;
	}
	

	public String getPropertiesFilePath() {
		return propertiesFilePath;
	}
	

	public void setPropertiesFilePath(String propertiesFilePath) {
		this.propertiesFilePath = propertiesFilePath;
	}
	
	
	

}
