package com.bekvon.bukkit.residence.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;

import com.bekvon.bukkit.residence.Residence;
import com.google.common.base.Charsets;

public class VersionChecker {
	Residence plugin;

	public VersionChecker(Residence plugin) {
		this.plugin = plugin;
	}

	public void VersionCheck(final Player player) {
		Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
			@Override
			public void run() {
				String readURL = "http://ci.citycraft.cn:8800/jenkins/job/Residence-Fix/lastSuccessfulBuild/artifact/src/plugin.yml";
				FileConfiguration config;
				String currentVersion = plugin.getDescription().getVersion();
				try {
					URL url = new URL(readURL);
					BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),
							Charsets.UTF_8));
					config = YamlConfiguration.loadConfiguration(br);
					String newVersion = config.getString("version");
					br.close();
					if (!newVersion.equals(currentVersion)) {
						String[] msg = new String[] {
								ChatColor.GREEN + "领地插件最新版本 v" + newVersion,
								ChatColor.RED + "服务器运行版本: v" + currentVersion,
								ChatColor.GOLD + "插件更新网站: " + ChatColor.BLUE
										+ plugin.getDescription().getWebsite(),
								ChatColor.YELLOW
										+ "查看最新修改: "
										+ ChatColor.BLUE
										+ "http://ci.citycraft.cn:8800/jenkins/job/Residence-Fix/changes" };
						if (player != null) {
							player.sendMessage(msg);
						} else {
							plugin.consoleMessage(msg);
						}
					}
				} catch (IOException e) {
					plugin.getLogger().warning("版本更新检查失败!");
				}
			}
		});
	}

}
