package com.l2jfrozen.gameserver.model.entity.tops;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import com.l2jfrozen.Config;
import com.l2jfrozen.gameserver.model.L2World;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
import com.l2jfrozen.gameserver.model.actor.instance.L2ItemInstance;
import com.l2jfrozen.gameserver.network.SystemMessageId;
import com.l2jfrozen.gameserver.network.serverpackets.InventoryUpdate;
import com.l2jfrozen.gameserver.network.serverpackets.SystemMessage;
import com.l2jfrozen.gameserver.thread.ThreadPoolManager;
import com.l2jfrozen.util.CloseUtil;
import com.l2jfrozen.util.database.L2DatabaseFactory;




public class MMOTop
{
	BufferedReader reader;
	public static Logger _log = Logger.getLogger(MMOTop.class.getName());
	public static MMOTop ourInstance = new MMOTop();

	public static MMOTop getInstance()
	{
		return ourInstance;
	}

	public MMOTop()
	{
		ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new startParce(), 60000, Config.MMOTOP_REFRESHTIME * 60 * 1000);
	}
	
	public void getPage(String address)
	{
		try
		{
			URL url = new URL(address);
			reader = new BufferedReader(new InputStreamReader(url.openStream(), "windows-1251"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void parse()
	{
		int i = 0;
		try
		{
			String line;
			while ((line = reader.readLine()) != null)
			{
				StringTokenizer st = new StringTokenizer(line, "\t. :");
				while (st.hasMoreTokens())
				{
					try
					{
						st.nextToken();
						int day = Integer.parseInt(st.nextToken());
						int month = Integer.parseInt(st.nextToken());
						int year = Integer.parseInt(st.nextToken());
						int hour = Integer.parseInt(st.nextToken());
						int minute = Integer.parseInt(st.nextToken());
						int second = Integer.parseInt(st.nextToken());
						st.nextToken();
						st.nextToken();
						st.nextToken();
						st.nextToken();
						String name = st.nextToken();

						L2PcInstance player = L2World.getInstance().getPlayer(name);
						if ((player != null) && (player.isOnline() == 1))
						{
							Calendar calendar = Calendar.getInstance();
							calendar.set(Calendar.YEAR, year);
							calendar.set(Calendar.MONTH, month);
							calendar.set(Calendar.DAY_OF_MONTH, day);
							calendar.set(Calendar.HOUR_OF_DAY, hour);
							calendar.set(Calendar.MINUTE, minute);
							calendar.set(Calendar.SECOND, second);
							calendar.set(Calendar.MILLISECOND, 0);
							long time = calendar.getTimeInMillis() / 1000L;
							checkAndSave(name, time);
						}
						i++;
					}
					catch (Exception e)
					{
					}
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void checkAndSave(String name, long time)
	{
		Connection con = null;
		PreparedStatement statement = null;
		ResultSet rs = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			statement = con.prepareStatement("SELECT * FROM `mmotop_votes` WHERE `name`=? AND `time`=? LIMIT 1");
			statement.setString(1, name);
			statement.setLong(2, time);
			rs = statement.executeQuery();
			if (!rs.next())
			{
				L2PcInstance player = L2World.getInstance().getPlayer(name);
				L2ItemInstance item = null;
				if ((player != null) && (player.isOnline() == 1))
				{
					item = player.getInventory().addItem("MMOTop", Config.MMOTOP_ITEM, Config.MMOTOP_MIN_COUNT, null, null);
					InventoryUpdate iu = new InventoryUpdate();
		            iu.addItem(item);
					player.sendPacket(iu);
					player.sendMessage("Вам начислено " + Config.MMOTOP_ITEM + " " + item.getItemName() + " за голосование в рейтинге MMOTop.");
					SystemMessage sm = new SystemMessage(SystemMessageId.YOU_PICKED_UP_S1_S2);
					sm.addItemName(Config.MMOTOP_ITEM);
		            sm.addNumber(Config.MMOTOP_MIN_COUNT);
		            player.sendPacket(sm);
		            
		            statement = con.prepareStatement("INSERT INTO `character_mmotop_votes` (`name`, `time`) VALUES (?, ?)");
		            statement.setString(1, name);
		            statement.setLong(2, time);
		            statement.execute();
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally 
		{
			CloseUtil.close(con);
			con = null;
		}
	}
		
	public class startParce implements Runnable
	{
		public startParce()
		{
		}

		public void run()
		{
			try
			{
				_log.info("MMOTop: Checking la2.mmotop.ru....");
				getPage(Config.MMOTOP_URL);
				parse();
			}
			catch (Exception e)
		    {
		    	e.printStackTrace();
		    }
		}
	}
}
