package org.w3c.dbwg.wsdl.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class ModSOAPImpl {

	/**
	 * @param args
	 * args[0] - name and path of file to be modified
	 */
	static String returnVal = "";
	static boolean foundit = false;
	public static void main(String[] args) {
		
		if (args.length < 1) {
			System.out.println("Supply the impl file to be modified ");
			System.exit(1);
		}
		String inputFile = args[0];
  	  	int x = inputFile.indexOf(".java");
  	  	String outputFile = inputFile.substring(0,x) + "Temp.java";
		File in = new File(inputFile);
		File out = new File(outputFile);
		String str = null;
		// read each record and parse
		try {
			BufferedWriter output = new BufferedWriter(new FileWriter(out));
			BufferedReader input = new BufferedReader(new FileReader(in));
			while (null != ((str = input.readLine()))) {
				parse(str, output);
			}
			output.close();
			input.close();
		} catch (Exception e) {
			System.out.println("Error=" +e.getMessage());
		}
		// copy new file back
		try {
	        // Create channel on the source
	        FileChannel srcChannel = new FileInputStream(outputFile).getChannel();
	        // Create channel on the destination
	        FileChannel dstChannel = new FileOutputStream(inputFile).getChannel();
	        // Copy file contents from source to destination
	        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
	        // Close the channels
	        srcChannel.close();
	        dstChannel.close();
	        // delete the old file
	        out.delete();
	        
	    } catch (IOException e) {
			System.out.println("Error=" +e.getMessage());
	    }		
 	  	System.out.println("successfully created echoes!");
	}
	private static void parse(String str, BufferedWriter output) {

		String find = ") throws java.rmi.RemoteException";
		int pos = str.indexOf(find);
		int strt = str.indexOf("(");
		try {
			if ((pos>=0) && (strt>=0)) {
				String arguments = str.substring(strt+1,pos);
				int space = arguments.indexOf(" ");
				returnVal = arguments.substring(space);
//				System.out.println("Testing example " + returnVal);
				output.write(str + "\r\n");
				foundit = true;
				return;
			} else {
				if (foundit) {
					str = str.replaceAll("null", returnVal);
					foundit = false;
				}
				output.write(str + "\r\n");
				return;
			}
		} catch (Exception e) {
			System.out.println("Error:" + e.getMessage());
		}
		return;
	}

}
