/*
 * Copyright (C) 2004-2014 L2J DataPack
 * 
 * This file is part of L2J DataPack.
 * 
 * L2J DataPack is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * L2J DataPack is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package handlers.admincommandhandlers;

import java.util.Calendar;
import java.util.List;
import java.util.StringTokenizer;

import com.l2jserver.gameserver.handler.IAdminCommandHandler;
import com.l2jserver.gameserver.instancemanager.GlobalVariablesManager;
import com.l2jserver.gameserver.instancemanager.TerritoryWarManager;
import com.l2jserver.gameserver.model.TerritoryWard;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;

/**
 * Admin comand handler for Territory War System This class handles following admin commands:
 * @author Gigiikun
 */
public class AdminTerritoryWar implements IAdminCommandHandler
{
	private static final String[] _adminCommands =
	{
		"admin_territory_war",
		"admin_territory_war_time",
		"admin_territory_war_start",
		"admin_territory_war_end",
		"admin_territory_wards_list"
	};
	
	@Override
	public boolean useAdminCommand(final String _command, L2PcInstance activeChar)
	{
		StringTokenizer st = new StringTokenizer(_command);
		String command = st.nextToken();
		
		if (command.equals("admin_territory_war"))
		{
			showMainPage(activeChar);
		}
		else if (command.equalsIgnoreCase("admin_territory_war_time"))
		{
			// territorywartime.htm
			if (st.hasMoreTokens())
			{
				final Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(TerritoryWarManager.getInstance().getTWStartTimeInMillis());
				
				final String val = st.nextToken();
				
				if ("month".equals(val))
				{
					cal.add(Calendar.MONTH, Integer.parseInt(st.nextToken()));
				}
				else if ("day+".equals(val))
				{
					cal.add(Calendar.DAY_OF_MONTH, Integer.parseInt(st.nextToken()));
				}
				else if ("day".equals(val))
				{
					int day = Integer.parseInt(st.nextToken());
					if ((cal.getActualMinimum(Calendar.DAY_OF_MONTH) > day) || (cal.getActualMaximum(Calendar.DAY_OF_MONTH) < day))
					{
						activeChar.sendMessage("Unable to change Siege Date - Incorrect day value only " + cal.getActualMinimum(Calendar.DAY_OF_MONTH) + "-" + cal.getActualMaximum(Calendar.DAY_OF_MONTH) + " is accepted!");
						return false;
					}
					cal.set(Calendar.DAY_OF_MONTH, day);
				}
				else if ("hour".equals(val))
				{
					int hour = Integer.parseInt(st.nextToken());
					if ((cal.getActualMinimum(Calendar.HOUR_OF_DAY) > hour) || (cal.getActualMaximum(Calendar.HOUR_OF_DAY) < hour))
					{
						activeChar.sendMessage("Unable to change Siege Date - Incorrect hour value only " + cal.getActualMinimum(Calendar.HOUR_OF_DAY) + "-" + cal.getActualMaximum(Calendar.HOUR_OF_DAY) + " is accepted!");
						return false;
					}
					cal.set(Calendar.HOUR_OF_DAY, hour);
				}
				else if ("min".equals(val))
				{
					int min = Integer.parseInt(st.nextToken());
					if ((cal.getActualMinimum(Calendar.MINUTE) > min) || (cal.getActualMaximum(Calendar.MINUTE) < min))
					{
						activeChar.sendMessage("Unable to change Siege Date - Incorrect minute value only " + cal.getActualMinimum(Calendar.MINUTE) + "-" + cal.getActualMaximum(Calendar.MINUTE) + " is accepted!");
						return false;
					}
					cal.set(Calendar.MINUTE, min);
				}
				
				if (cal.getTimeInMillis() < System.currentTimeMillis())
				{
					activeChar.sendMessage("Unable to change TW Date!");
				}
				else if (cal.getTimeInMillis() != TerritoryWarManager.getInstance().getTWStartTimeInMillis())
				{
					TerritoryWarManager.getInstance().setTWStartTimeInMillis(cal.getTimeInMillis());
					GlobalVariablesManager.getInstance().set(TerritoryWarManager.GLOBAL_VARIABLE, cal.getTimeInMillis());
					activeChar.sendMessage("Territory War Date has been changed.");
				}
			}
			showSiegeTimePage(activeChar);
		}
		else if (command.equalsIgnoreCase("admin_territory_war_start"))
		{
			TerritoryWarManager.getInstance().setTWStartTimeInMillis(System.currentTimeMillis());
		}
		else if (command.equalsIgnoreCase("admin_territory_war_end"))
		{
			TerritoryWarManager.getInstance().setTWStartTimeInMillis(System.currentTimeMillis() - TerritoryWarManager.WARLENGTH);
		}
		else if (command.equalsIgnoreCase("admin_territory_wards_list"))
		{
			// build beginning of html page
			final NpcHtmlMessage npcHtmlMessage = new NpcHtmlMessage();
			StringBuilder sb = new StringBuilder(256);
			sb.append("<html><title>Territory War</title><body><br><center><font color=\"LEVEL\">Active Wards List:</font></center>");
			
			// get,build & send current Wards list
			if (TerritoryWarManager.getInstance().isTWInProgress())
			{
				List<TerritoryWard> territoryWardList = TerritoryWarManager.getInstance().getAllTerritoryWards();
				for (TerritoryWard ward : territoryWardList)
				{
					if (ward.getNpc() != null)
					{
						sb.append("<table width=270><tr>"
							+ "<td width=135 ALIGN=\"LEFT\">").append(ward.getNpc().getName()).append("</td>"
							+ "<td width=135 ALIGN=\"RIGHT\"><button value=\"TeleTo\" action=\"bypass -h admin_move_to ").append(ward.getNpc().getX()).append(' ').append(ward.getNpc().getY()).append(' ').append(ward.getNpc().getZ()).append("\" width=50 height=21 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_ct1.button_df\"></td>"
							+ "</tr></table>");
					}
					else if (ward.getPlayer() != null)
					{
						sb.append("<table width=270><tr>"
							+ "<td width=135 ALIGN=\"LEFT\">").append(ward.getPlayer().getActiveWeaponInstance().getItemName()).append(" - ").append(ward.getPlayer().getName()).append("</td>"
							+ "<td width=135 ALIGN=\"RIGHT\"><button value=\"TeleTo\" action=\"bypass -h admin_move_to ").append(ward.getPlayer().getX()).append(' ').append(ward.getPlayer().getY()).append(' ').append(ward.getPlayer().getZ()).append("\" width=50 height=21 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_ct1.button_df\"></td>"
							+ "</tr></table>");
					}
				}
				sb.append("<br><center><button value=\"Back\" action=\"bypass -h admin_territory_war\" width=50 height=21 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_ct1.button_df\"></center></body></html>");
				npcHtmlMessage.setHtml(sb.toString());
				activeChar.sendPacket(npcHtmlMessage);
			}
			else
			{
				sb.append("<br><br><center>The Ward List is empty!<br>TW has probably NOT started!"
					+ "<br><button value=\"Back\" action=\"bypass -h admin_territory_war\" width=50 height=21 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_ct1.button_df\"></center></body></html>");
				npcHtmlMessage.setHtml(sb.toString());
				activeChar.sendPacket(npcHtmlMessage);
			}
		}
		return true;
	}
	
	@Override
	public String[] getAdminCommandList()
	{
		return _adminCommands;
	}
	
	private void showSiegeTimePage(L2PcInstance activeChar)
	{
		final NpcHtmlMessage adminReply = new NpcHtmlMessage();
		adminReply.setFile(activeChar.getHtmlPrefix(), "data/html/admin/territorywartime.htm");
		
		// <table><tr>%calendar%</tr></table>
		final String BUTTON = "<td width=35><button value=\"\1\" action=\"bypass admin_territory_war_time day \1\" width=35 height=21 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>" + AdminSiege.CR;
		final String CURRENT = "<td align=center><font color=LEVEL>\1</font></td>" + AdminSiege.CR;
		adminReply.replace("%calendar%", AdminSiege.calendarHtmlTable(TerritoryWarManager.getInstance().getTWStart(), BUTTON, CURRENT));
		
		adminReply.replace("%time%", com.l2jserver.util.Util.dateFormat(TerritoryWarManager.getInstance().getTWStart()));
		activeChar.sendPacket(adminReply);
	}
	
	private void showMainPage(L2PcInstance activeChar)
	{
		AdminHtml.showAdminHtml(activeChar, "territorywar.htm");
	}
}
