package org.jerrymouse.cc.site.store.file;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.jerrymouse.cc.site.store.StoreManager;

public class FileStoreManager extends StoreManager {
	private String username;
	private String dir = ".cc-store";

	public FileStoreManager(String username) {
		this.username = username;
	}

	@Override
	public byte[] getBytes(String filename) {
		File file = getFile(filename);
		try {
			return IOUtils.toByteArray(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void putBytes(String filename, byte[] bytes) {
		File file = getFile(filename);
		try {
			IOUtils.copy(new ByteArrayInputStream(bytes), new FileOutputStream(
					file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private File getDir() {
		File file = new File((String) System.getProperties().get("user.home"));
		file = new File(file.getAbsolutePath() + "/" + dir);
		if (!file.exists()) {
			file.mkdir();
		}
		return file;
	}

	private File getFile(String filename) {
		File file = getDir();
		file = new File(file.getAbsolutePath() + "/" + username + "-"
				+ filename);
		return file;
	}
}
