

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.NoFilepatternException;
import org.eclipse.jgit.errors.NoWorkTreeException;
import org.eclipse.jgit.lib.StoredConfig;

public class JGitExperiment {

	private File repoDir;
	Git db;
	private StoredConfig config;

	public JGitExperiment(File repo) {
		this.repoDir = repo;
		if (!this.repoDir.exists())
			this.repoDir.mkdirs();
		this.db = Git.init().setDirectory(this.repoDir).setBare(false).call();
		this.config = db.getRepository().getConfig();
	}
	
	public Git getGit() {
		return db;
	}

	public void addFileToDb(String filepattern) throws NoFilepatternException {
		this.db.add().addFilepattern(filepattern).setUpdate(false).call();
	}

	public void createNewFile(String name, String dir) {

		if(dir == null)
			dir = "";
		
		repoDir = new File(repoDir, dir);

		repoDir.mkdirs();

		try {
			FileOutputStream fos = new FileOutputStream(new File(repoDir, name));

			fos.write(name.getBytes());
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public StoredConfig getConfig() {
		return this.config;
	}

	public String getStatus() {
		StringBuilder sb = new StringBuilder();
		try {
			Status stat = this.db.status().call();

			Iterator<?> it = stat.getAdded().iterator();

			sb.append("\nAdded:");

			while (it.hasNext()) {
				sb.append("\n" + it.next());
			}

			it = stat.getChanged().iterator();

			sb.append("\nChanged:");

			while (it.hasNext()) {
				sb.append("\n" + it.next());
			}

			it = stat.getModified().iterator();

			sb.append("\nModified:");

			while (it.hasNext()) {
				sb.append("\n" + it.next());
			}

			it = stat.getUntracked().iterator();

			sb.append("\nUntracked:");

			while (it.hasNext()) {
				sb.append("\n" + it.next());
			}
		} catch (NoWorkTreeException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

}
