package org.ourfilesystem.simpleui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.ourfilesystem.utilities.FileUtils;

public class VersionUpdater {
	
	public static String Version = "0.4";
	public static String VersionFile = "version.txt";
	
	public static void update(String basedir) throws Exception {
		String readversion = "";
		File vf = new File(basedir + File.separator + VersionFile);
		if (vf.exists()) {
			BufferedReader br = new BufferedReader(new FileReader(vf));
			readversion = br.readLine();
			br.close();
		}
		if (!Version.equals(readversion) && Version.equals("0.4")) {
			doUpdate04(basedir);
		}
		writeNewVersion(basedir);
	}
	
	public static void writeNewVersion(String basedir) throws Exception {
		File vf = new File(basedir + File.separator + VersionFile);
		PrintStream ps = new PrintStream(vf);
		ps.println(Version);
		ps.close();
	}
	
	public static void doUpdate04(String basedir) throws IOException {
		File bd = new File(basedir);
		bd.mkdirs();
		File searchtemplate = new File(basedir + File.separator + "search.template");
		if (searchtemplate.exists()) {
			Matcher dm = Pattern.compile("\\s*DATES\\s*").matcher("");
			Matcher pm = Pattern.compile("\\s*PDATES\\s*").matcher("");
			File backup = new File(basedir + File.separator + "search.template.bak");
			FileUtils.copyFile(searchtemplate, backup, false);
			BufferedReader br = new BufferedReader(new FileReader(backup));
			PrintStream ps = new PrintStream(searchtemplate);
			String line = br.readLine();
			ps.println("DATES");
			ps.println("PDATES");
			while (line != null) {
				dm.reset(line);
				pm.reset(line);
				if (!dm.find() && !pm.find()) {
					ps.println(line);
				}
				line = br.readLine();
			}
			ps.close();
			br.close();
		}
		else {
			WriteDefaultSearchTemplate.writeDefaultFile(searchtemplate);
		}
	}

}
