package fr.xephi.authme.settings;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;

import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;

public class CustomConfiguration extends YamlConfiguration {

	private final File configFile;

	public CustomConfiguration(final File file) {
		this.configFile = file;
		load();
	}

	public File getConfigFile() {
		return configFile;
	}

	public void load() {
		try {
			super.load(configFile);
		} catch (final FileNotFoundException e) {
			ConsoleLogger.showError("未找到配置文件 " + configFile.getName() + ", 创建新文件...");
			reLoad();
		} catch (final IOException e) {
			ConsoleLogger.showError("无法载入配置文件 " + configFile.getName());
		} catch (final InvalidConfigurationException e) {
			ConsoleLogger.showError(configFile.getName() + " 不是一个有效的配置文件");
		}
	}

	public boolean loadResource(final File file) {
		if (!file.exists()) {
			try {
				if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
					return false;
				}
				final int i = file.getPath().indexOf("AuthMe");
				if (i > -1) {
					final String path = file.getPath().substring(i + 6).replace('\\', '/');
					final InputStream is = AuthMe.class.getResourceAsStream(path);
					Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
					return true;
				}
			} catch (final Exception e) {
				ConsoleLogger.writeStackTrace(e);
				ConsoleLogger.showError("从 JAR 载入配置文件失败...");
			}
		}
		return false;
	}

	public boolean reLoad() {
		boolean out = true;
		if (!configFile.exists()) {
			out = loadResource(configFile);
		}
		if (out) {
			load();
		}
		return out;
	}

	public void save() {
		try {
			super.save(configFile);
		} catch (final IOException ex) {
			ConsoleLogger.showError("无法保存配置文件 " + configFile.getName());
		}
	}
}
