package cn.citycraft.AuthMe.converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.bukkit.command.CommandSender;

import cn.citycraft.AuthMe.AuthMe;
import cn.citycraft.AuthMe.ConsoleLogger;
import cn.citycraft.AuthMe.cache.auth.PlayerAuth;
import cn.citycraft.AuthMe.datasource.DataSource;
import cn.citycraft.AuthMe.settings.Settings;

/**
 * @author Xephi59
 */
public class CrazyLoginConverter implements Converter {

	public DataSource database;
	public AuthMe instance;
	public CommandSender sender;

	public CrazyLoginConverter(final AuthMe instance, final CommandSender sender) {
		this.instance = instance;
		this.database = instance.database;
		this.sender = sender;
	}

	public CrazyLoginConverter getInstance() {
		return this;
	}

	@Override
	public void run() {
		final String fileName = Settings.crazyloginFileName;
		try {
			final File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
			if (!source.exists()) {
				sender.sendMessage("转换 CrazyLogin 数据时发生错误, 请把文件 " + fileName + " 放在 plugin/AuthMe 文件夹!");
				return;
			}
			String line;
			final BufferedReader users = new BufferedReader(new FileReader(source));
			while ((line = users.readLine()) != null) {
				if (line.contains("|")) {
					final String[] args = line.split("\\|");
					if (args.length < 2) {
						continue;
					}
					if (args[0].equalsIgnoreCase("name")) {
						continue;
					}
					final String playerName = args[0].toLowerCase();
					final String psw = args[1];
					if (psw != null) {
						final PlayerAuth auth = new PlayerAuth(playerName, psw, "127.0.0.1", System.currentTimeMillis(), playerName);
						database.saveAuth(auth);
					}
				}
			}
			users.close();
			ConsoleLogger.info("CrazyLogin 数据导入完成...");
		} catch (final IOException ex) {
			ConsoleLogger.showError(ex.getMessage());
			ConsoleLogger.showError("转换 CrazyLogin 数据时发生错误, 请确认文件是否正确...");
		}
	}

}
