package ch.ntb.inf.deep.eclipse.ui.properties;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ClasspathFileChanger {
	private BufferedReader configFile;
	private BufferedWriter out;
	private StringBuffer fileContent;
	//private int count;
	
	public ClasspathFileChanger(String file) {
		try {
			//count = 0;
			fileContent = new StringBuffer();
			configFile = new BufferedReader(new FileReader(file));
			
			int ch  = configFile.read();
			while(ch  != -1){
				fileContent.append((char)ch);
				ch = configFile.read();
				//count++;
			}
			configFile.close();
			out = new BufferedWriter(new FileWriter(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void changeLibPath(String oldPath, String newPath) throws IOException{
		String key = "<classpathentry kind=\"lib\" path=\"";
		int indexOfKey = fileContent.indexOf(key + oldPath);
		if(indexOfKey > -1){
			int indexOfEndtoken = fileContent.indexOf("/>", indexOfKey);
			fileContent.replace(indexOfKey, indexOfEndtoken, key + newPath + "/bin\"");
		}else{
			throw new IOException();
		}
	}
	
	public void save(){
		try {
			out.write(fileContent.toString());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void close(){
		try {
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

@@ -99,32 +99,54 @@
 ufferedWriter;%0D%0A
+import java.io.File;%0D%0A
 import java.io.F
@@ -1222,16 +1222,225 @@
 fKey);%0D%0A
+%09%09%09File srcFolder = new File(newPath + %22/src%22);%0D%0A%09%09%09if(srcFolder.exists())%7B%0D%0A%09%09%09%09fileContent.replace(indexOfKey, indexOfEndtoken, key + newPath + %22/bin%5C%22 sourcepath=%5C%22%22 + newPath + %22/src%5C%22%22);%0D%0A%09%09%09%7Delse%7B%09%09%09%09%0D%0A%09
 %09%09%09fileC
@@ -1511,16 +1511,22 @@
 n%5C%22%22);%0D%0A
+%09%09%09%7D%0D%0A
 %09%09%7Delse%7B

change sourcepath in .classpath too