// file replace utility quickhack
package com.db4o.lib;

import java.io.RandomAccessFile;

public class CrepFile
{
	private String i_filePath;
	
	private String i_replaceEnd = "";
	private String i_replaceDate = "";
	
	boolean i_ok;
	
	public CrepFile(String a_filePath){
		i_filePath = a_filePath;
		i_ok = true;
	}
	
	public void replace(String a_replace, String a_with){
		Str str = null;
		RandomAccessFile raf = null;
		int len = 0;
		byte l_bytes[] = null;
		if (i_ok){
			
			a_with = parseReplace(a_with);
			
			try{
				if(!(new File(i_filePath).exists())){
					throw new Exception();
				}
				raf = new RandomAccessFile(i_filePath,"rw");
			}
			catch(Exception l_ex){
				Crep.mmm("File not found:" + i_filePath);
				return;
			}
			
			try{
				len = (int)raf.length();
				l_bytes = new byte[len];
				raf.read(l_bytes,0,len);
				raf.close();
			}
			catch(Exception l_ex){
				Crep.mmm("File read denied:" + i_filePath);
				return;
			}
			
			str = new Str(new String(l_bytes));
			
			if (i_replaceEnd.length() > 0){
				str.replace(a_replace,i_replaceEnd,a_with);
			}
			else
			{
				str.replace(a_replace,a_with);
			}
			
			l_bytes = str.getString().getBytes();
			
			try{
					new File(i_filePath).delete();
				}
			catch(Exception l_ex){
				Crep.mmm("File access denied:" + i_filePath);
				return;
			}
			
			try{
				raf = new RandomAccessFile(i_filePath,"rw");
				raf.write(l_bytes);
				raf.close();
			}
			catch(Exception l_ex){
				Crep.mmm("File access denied:" + i_filePath);
				return;
			}

		}
		else{
			Crep.onError();
		}
	}

	
	public void setOption(String a_option){
		String option;
		try{
			option = a_option.substring(0,3);
			if (option.equals("-e:")){
				i_replaceEnd = a_option.substring(3);
				return;
			}
			if (option.equals("-d:")){
				i_replaceDate = a_option.substring(3);
				return;
			}
			throw new Exception();
		}
		catch(Exception l_Ex){
			i_ok = false;
		}
	}
	
	public String parseReplace(String a_with){
		if (i_replaceDate.length() > 0){
			Str str = new Str(a_with);
			str.replace(i_replaceDate,new Str(new Date()).getString());
			a_with = str.getString();
		}
		return a_with;
	}
}

