/*
 * Copyright (C) 2005-2008 L2J_JP / 2008-2013 L2J-SFJP
 * 
 * This file is part of L2J Server.
 * 
 * L2J Server 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 Server 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 ai.individual;

import java.util.concurrent.Future;
import java.util.logging.Level;

import javolution.util.FastList;
import ai.npc.AbstractNpcAI;

import com.l2jserver.Config;
import com.l2jserver.gameserver.datatables.DoorTable;
import com.l2jserver.gameserver.datatables.NpcTable;
import com.l2jserver.gameserver.datatables.SpawnTable;
import com.l2jserver.gameserver.enums.QuestEventType;
import com.l2jserver.gameserver.instancemanager.GrandBossManager;
import com.l2jserver.gameserver.model.L2Spawn;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.actor.templates.L2NpcTemplate;
import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
import com.l2jserver.gameserver.model.zone.type.L2BossZone;
import com.l2jserver.gameserver.network.NpcStringId;
import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
import com.l2jserver.gameserver.network.serverpackets.ExShowScreenMessage;
import com.l2jserver.gameserver.network.serverpackets.L2GameServerPacket;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jserver.gameserver.network.serverpackets.NpcSay;

/**
 * Ice Fairy Sirra AI
 * @author Kerberos
 */
public class IceFairySirra extends AbstractNpcAI
{
	//22100 フレヤ ガーデナー
	//22101 フレヤ セクレタリー
	//22102 フレヤ セクレタリー
	//22104 フレヤズ ペット
	//22103 +フレヤ ベアー
	//29056 アイス フェアリー シルー/レイド ボス
	//29057 +アイス フェアリーの従者/レイド部下
	//29058 +アイス フェアリー ビーホルダー/レイド部下
	//29060 アイス クイーンの親衛隊長/レイド ボス
	
	private static final int SIRRA = 29056;		//シルー
	private static final int STEWARD = 32029;	//執事
	private static final int SILVER_HEMOCYTE = 8057;	//銀の血
	private static L2BossZone _sirrasZone;
	private static L2PcInstance _player = null;
	protected FastList<L2Npc> _allMobs = new FastList<>();
	protected Future<?> _onDeadEventTask = null;
	
	private IceFairySirra(int id, String name, String descr)
	{
		super(id, name, descr);
		int[] mob =
		{
			22100,
			22102,
			22104,
			29056
		};
		registerMobs(mob);
		registerMobs(new int[]
		{
			STEWARD
		}, QuestEventType.QUEST_START, QuestEventType.ON_TALK, QuestEventType.ON_FIRST_TALK);
		
		addKillId(SIRRA);
		String test = loadGlobalQuestVar("Sirra_Respawn");
		if (test.length() > 0)
		{
			long remain = Long.parseLong(test) - System.currentTimeMillis();
			if (remain <= 0)
			{
				init(false);
			}
			else
			{
				init(true);
				startQuestTimer("respawn", remain, null, null);
			}
		}
		else
		{
			init(false);
		}
	}
	
	public void init(boolean isBusy)
	{
		_sirrasZone = GrandBossManager.getInstance().getZone(105546, -127892, -2768);
		if (_sirrasZone == null)
		{
			_log.warning("IceFairySirraManager: Failed to load zone");
			return;
		}
		_sirrasZone.setEnabled(false);
		L2Npc steward = findTemplate(STEWARD);
		if (steward != null)
		{
			steward.setBusy(isBusy);
		}
		openGates();
	}
	
	public void cleanUp()
	{
		init(false);
		cancelQuestTimer("30MinutesRemaining", null, _player);
		cancelQuestTimer("20MinutesRemaining", null, _player);
		cancelQuestTimer("10MinutesRemaining", null, _player);
		cancelQuestTimer("End", null, _player);
		for (L2Npc mob : _allMobs)
		{
			try
			{
				mob.getSpawn().stopRespawn();
				mob.deleteMe();
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "IceFairySirraManager: Failed deleting mob.", e);
			}
		}
		_allMobs.clear();
	}
	
	public L2Npc findTemplate(int npcId)
	{
		L2Spawn s = SpawnTable.getInstance().getFirstSpawn(npcId);
		if (s == null) return null;
		return s.getLastSpawn();
	}
	
	protected void openGates()
	{
		for (int i = 23140001; i < 23140003; i++)
		{
			try
			{
				L2DoorInstance door = DoorTable.getInstance().getDoor(i);
				if (door != null)
				{
					door.openMe();
				}
				else
				{
					_log.warning("IceFairySirraManager: Attempted to open undefined door. doorId: " + i);
				}
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "IceFairySirraManager: Failed closing door", e);
			}
		}
	}
	
	protected void closeGates()
	{
		for (int i = 23140001; i < 23140003; i++)
		{
			try
			{
				L2DoorInstance door = DoorTable.getInstance().getDoor(i);
				if (door != null)
				{
					door.closeMe();
				}
				else
				{
					_log.warning("IceFairySirraManager: Attempted to close undefined door. doorId: " + i);
				}
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, "IceFairySirraManager: Failed closing door", e);
			}
		}
	}
	
	public boolean checkItems(L2PcInstance player)
	{
		if (player.getParty() != null)
		{
			for (L2PcInstance pc : player.getParty().getMembers())
			{
				L2ItemInstance i = pc.getInventory().getItemByItemId(SILVER_HEMOCYTE);
				if ((i == null) || (i.getCount() < 10))
				{
					return false;
				}
			}
		}
		else
		{
			return false;
		}
		return true;
	}
	
	public void destroyItems(L2PcInstance player)
	{
		if (player.getParty() != null)
		{
			for (L2PcInstance pc : player.getParty().getMembers())
			{
				L2ItemInstance i = pc.getInventory().getItemByItemId(SILVER_HEMOCYTE);
				pc.destroyItem("Hemocytes", i.getObjectId(), 10, null, false);
			}
		}
		else
		{
			cleanUp();
		}
	}
	
	public void teleportInside(L2PcInstance player)
	{
		if (player.getParty() != null)
		{
			for (L2PcInstance pc : player.getParty().getMembers())
			{
			//	pc.teleToLocation(113533, -126159, -3488, false);
				if (_sirrasZone == null)
				{
					_log.warning("IceFairySirraManager: Failed to load zone");
					cleanUp();
					return;
				}
				_sirrasZone.allowPlayerEntry(pc, 2103);
				pc.teleToLocation(113533, -126159, -3488, false);
			}
		}
		else
		{
			cleanUp();
		}
	}
	
	public void screenMessage(L2PcInstance player, NpcStringId npcString, int time)
	{
		if (player.getParty() != null)
		{
			L2GameServerPacket packet = new ExShowScreenMessage(npcString, 2, time);
			for (L2PcInstance pc : player.getParty().getMembers())
				pc.sendPacket(packet);
		}
		else
		{
			cleanUp();
		}
	}
	
	public void doSpawns()
	{
		int[][] mobs =
		{
			{
				29060,
				105546,
				-127892,
				-2768
			},
			{
				29056,
				102779,
				-125920,
				-2840
			},
			{
				22100,
				111719,
				-126646,
				-2992
			},
			{
				22102,
				109509,
				-128946,
				-3216
			},
			{
				22104,
				109680,
				-125756,
				-3136
			}
		};
		L2Spawn spawnDat;
		L2NpcTemplate template;
		try
		{
			for (int i = 0; i < 5; i++)
			{
				template = NpcTable.getInstance().getTemplate(mobs[i][0]);
				if (template != null)
				{
					spawnDat = new L2Spawn(template);
					spawnDat.setAmount(1);
					spawnDat.setX(mobs[i][1]);
					spawnDat.setY(mobs[i][2]);
					spawnDat.setZ(mobs[i][3]);
					spawnDat.setHeading(0);
					spawnDat.setRespawnDelay(60);
					SpawnTable.getInstance().addNewSpawn(spawnDat, false);
					_allMobs.add(spawnDat.doSpawn());
					spawnDat.stopRespawn();
				}
				else
				{
					_log.warning("IceFairySirraManager: Data missing in NPC table for ID: " + mobs[i][0]);
				}
			}
		}
		catch (Exception e)
		{
			_log.warning("IceFairySirraManager: Spawns could not be initialized: " + e);
		}
	}
	
	public String getHtmlPath(int val)	//[JOJO]
	{
		if (val == 0)
			return "data/html/default/32029.htm";
		else
			return "data/html/default/32029-" + val + ".htm";
	}
	
	public void sendHtml(L2Npc npc, L2PcInstance player, String filename)
	{
		NpcHtmlMessage html = new NpcHtmlMessage(npc.getObjectId());
		html.setFile(player.getHtmlPrefix(), filename);
		html.replace("%objectId%", npc.getObjectId());
		player.sendPacket(html);
		player.sendPacket(ActionFailed.STATIC_PACKET);
	}
	
	@Override
	public String onFirstTalk(L2Npc npc, L2PcInstance player)
	{
		player.setLastQuestNpcObject(npc.getObjectId());
		String filename;
		if (npc.isBusy())
		{
			if (player == _player || player.isInParty() && player.getParty().getLeader() == _player)	//+[JOJO]
				filename = getHtmlPath(10);
			else
				filename = getHtmlPath(90);	//+[JOJO]
		}
		else
		{
			filename = getHtmlPath(0);
		}
		sendHtml(npc, player, filename);
		return null;
	}
	
	@Override
	public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
	{
		if (event.equals("check_condition"))	//<<== data/html/default/32029.htm
		{
			if (npc.isBusy())// should never happen
			{
				sendHtml(npc, player, getHtmlPath(90));			//+[JOJO]
				return super.onAdvEvent(event, npc, player);
			}
			String filename;
			if (player.isInParty() && (player.getParty().getLeaderObjectId() == player.getObjectId()))
			{
				if (checkItems(player))
				{
					startQuestTimer("start", 100000, null, player);
					_player = player;
					destroyItems(player);
					player.getInventory().addItem("Scroll", /*石化スクロール*/8379, 3, player, null);
					npc.setBusy(true);
					screenMessage(player, NpcStringId.STEWARD_PLEASE_WAIT_A_MOMENT, 100000);
					filename = getHtmlPath(3);
					_sirrasZone.broadcastPacket(new NpcSay(0, 0, npc.getId(), NpcStringId.ATTENTION_PLEASE_THE_GATES_WILL_BE_CLOSING_SHORTLY_ALL_VISITORS_TO_THE_QUEENS_CASTLE_SHOULD_LEAVE_IMMEDIATELY));
				}
				else
				{
					filename = getHtmlPath(2);
				}
			}
			else
			{
				filename = getHtmlPath(1);
			}
			sendHtml(npc, player, filename);
		}
		else if (event == "start")
		{
			if (_sirrasZone == null)
			{
				_log.warning("IceFairySirraManager: Failed to load zone");
				cleanUp();
				return super.onAdvEvent(event, npc, player);
			}
			_sirrasZone.setEnabled(true);
			closeGates();
			doSpawns();
			startQuestTimer("Party_Port", 2000, null, player);
			startQuestTimer("End", 1802000, null, player);
		}
		else if (event == "Party_Port")
		{
			teleportInside(player);
			screenMessage(player, NpcStringId.STEWARD_PLEASE_RESTORE_THE_QUEENS_FORMER_APPEARANCE, 10000);
			startQuestTimer("30MinutesRemaining", 300000, null, player);
		}
		else if (event == "30MinutesRemaining")
		{
			screenMessage(player, NpcStringId.N30_MINUTES_REMAIN, 10000);
			startQuestTimer("20minutesremaining", 600000, null, player);
		}
		else if (event == "20MinutesRemaining")
		{
			screenMessage(player, NpcStringId.N20_MINUTES_REMAIN, 10000);
			startQuestTimer("10minutesremaining", 600000, null, player);
		}
		else if (event == "10MinutesRemaining")
		{
			screenMessage(player, NpcStringId.STEWARD_WASTE_NO_TIME_PLEASE_HURRY, 10000);
		}
		else if (event == "End")
		{
			screenMessage(player, NpcStringId.STEWARD_WAS_IT_INDEED_TOO_MUCH_TO_ASK, 10000);
			cleanUp();
		}
		else if (event == "respawn")
		{
			cleanUp();
		}
		return super.onAdvEvent(event, npc, player);
	}
	
	@Override
	public String onKill(L2Npc npc, L2PcInstance killer, boolean isPet)
	{
		if (npc.getId() == SIRRA)
		{
			cancelQuestTimer("30MinutesRemaining", null, _player);
			cancelQuestTimer("20MinutesRemaining", null, _player);
			cancelQuestTimer("10MinutesRemaining", null, _player);
			cancelQuestTimer("End", null, _player);
			for (L2Npc mob : _allMobs)
			{
				try
				{
					mob.getSpawn().stopRespawn();
					if (mob == npc)
						continue; /* Do animation task. (See com.l2jserver.gameserver.taskmanager.DecayTaskManager) */
					else
						mob.deleteMe();
				}
				catch (Exception e)
				{
					_log.log(Level.SEVERE, "IceFairySirraManager: Failed deleting mob.", e);
				}
			}
			_allMobs.clear();
			init(true);
			int respawnMinDelay = 43200000 * (int) (Config.RAID_MIN_RESPAWN_MULTIPLIER);
			int respawnMaxDelay = 129600000 * (int) (Config.RAID_MAX_RESPAWN_MULTIPLIER);
			int respawn_delay = getRandom(respawnMinDelay, respawnMaxDelay);
			saveGlobalQuestVar("Sirra_Respawn", String.valueOf(System.currentTimeMillis() + respawn_delay));
			startQuestTimer("respawn", respawn_delay, null, null);
			screenMessage(killer, NpcStringId.FREYA_HEATHENS_FEEL_MY_CHILL, 10000);
//保留		startQuestTimer("Win",30000,null, _player);
		}
//		else if (npc.getId() == 29060 /*アイス クイーンの親衛隊長*/)
//		{
//			//TODO:
//		}
		return super.onKill(npc, killer, isPet);
	}
	
//(未整理)1000400"フレヤ ベアー: 攻撃だ！攻撃！"
//(未整理)1000292"フレヤ ベアー: 命令に従います。"
//(未整理)1000292"フレヤ ベアー: 命令に従います。"
//(未整理)1000292"フレヤ ベアー: 命令に従います。"

	public static void main(String[] args)
	{
		new IceFairySirra(-1, "IceFairySirra", "ai");
	}
}