package charactermanaj.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * ファイルベースのユーザーデータの保存先の実装
 * @author seraphy
 */
public class FileUserData implements UserData {

	/**
	 * ロガー
	 */
	private static final Logger logger = Logger.getLogger(FileUserData.class.getName());

	/**
	 * 保存先ファイル
	 */
	private File file;

	public FileUserData(File file) {
		if (file == null) {
			throw new IllegalArgumentException();
		}
		this.file = file;
	}

	public File getFile() {
		return file;
	}

	@Override
	public boolean exists() {
		return file.exists() && file.isFile();
	}

	@Override
	public long lastModified() {
		return file.lastModified();
	}

	@Override
	public long length() {
		return file.length();
	}

	@Override
	public InputStream openStream() throws IOException {
		return new BufferedInputStream(new FileInputStream(file));
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		return new BufferedOutputStream(new FileOutputStream(file));
	}

	@Override
	public boolean delete() {
		try {
			if (exists()) {
				FileUtilities.delete(file);
			}
			return true;

		} catch (Exception ex) {
			// セキュリティ例外ぐらい.
			logger.log(Level.WARNING, "file removing failed." + file, ex);
			return false;
		}
	}

	@Override
	public String toString() {
		return "FileUserData{file:" + file + "}";
	}
}
