package cn.citycraft.AuthMe;

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.text.SimpleDateFormat;
import java.util.Date;

import cn.citycraft.AuthMe.settings.Settings;

/**
 *
 * @author stefano
 */
public class PerformBackup {

	private final SimpleDateFormat aformat = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
	private final String dateString = aformat.format(new Date());
	private final String dbName = Settings.getMySQLDatabase;
	private final String dbPassword = Settings.getMySQLPassword;
	private final String dbUserName = Settings.getMySQLUsername;
	private AuthMe instance;
	private final String path = AuthMe.getInstance().getDataFolder() + File.separator + "backups" + File.separator + "backup" + dateString;
	private final String tblname = Settings.getMySQLTablename;

	public PerformBackup(final AuthMe instance) {
		this.setInstance(instance);
	}

	public boolean doBackup() {

		switch (Settings.getDataSource) {
		case FILE:
			return FileBackup("auths.db");
		case MYSQL:
			return MySqlBackup();
		case SQLITEHIKARI:
		case SQLITE:
			return FileBackup(Settings.getMySQLDatabase + ".db");
		}

		return false;
	}

	public AuthMe getInstance() {
		return instance;
	}

	public void setInstance(final AuthMe instance) {
		this.instance = instance;
	}

	/*
	 * Check if we are under Windows and correct location of mysqldump.exe
	 * otherwise return error.
	 */
	private boolean checkWindows(final String windowsPath) {
		final String isWin = System.getProperty("os.name").toLowerCase();
		if (isWin.indexOf("win") >= 0) {
			if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) {
				return true;
			} else {
				ConsoleLogger.showError("Mysql Windows Path is incorrect please check it");
				return true;
			}
		} else {
			return false;
		}
	}

	private boolean FileBackup(final String backend) {
		final File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");

		if (!dirBackup.exists()) {
			dirBackup.mkdirs();
		}

		try {
			copy(new File("plugins" + File.separator + "AuthMe" + File.separator + backend), new File(path + ".db"));
			return true;
		} catch (final Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}

	private boolean MySqlBackup() {
		final File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups");

		if (!dirBackup.exists()) {
			dirBackup.mkdir();
		}
		if (checkWindows(Settings.backupWindowsPath)) {
			final String executeCmd = Settings.backupWindowsPath + "\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
			Process runtimeProcess;
			try {
				runtimeProcess = Runtime.getRuntime().exec(executeCmd);
				final int processComplete = runtimeProcess.waitFor();
				if (processComplete == 0) {
					ConsoleLogger.info("备份创建成功.");
					return true;
				} else {
					ConsoleLogger.showError("无法创建备份!");
				}
			} catch (final Exception ex) {
				ex.printStackTrace();
			}
		} else {
			final String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql";
			Process runtimeProcess;
			try {
				runtimeProcess = Runtime.getRuntime().exec(executeCmd);
				final int processComplete = runtimeProcess.waitFor();
				if (processComplete == 0) {
					ConsoleLogger.info("备份创建成功.");
					return true;
				} else {
					ConsoleLogger.showError("无法创建备份!");
				}
			} catch (final Exception ex) {
				ex.printStackTrace();
			}
		}
		return false;
	}

	/*
	 * Copyr src bytefile into dst file
	 */
	void copy(final File src, final File dst) throws IOException {
		final InputStream in = new FileInputStream(src);
		final OutputStream out = new FileOutputStream(dst);

		// Transfer bytes from in to out
		final byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
	}

}
