/*
 * This program 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.
 * 
 * This program 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 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.instancemanager.GrandBossManager;
import com.l2jserver.gameserver.model.L2ItemInstance;
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.quest.Quest;
import com.l2jserver.gameserver.model.zone.type.L2BossZone;
import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
import com.l2jserver.gameserver.network.serverpackets.CreatureSay;
import com.l2jserver.gameserver.network.serverpackets.ExShowScreenMessage;
import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jserver.gameserver.templates.chars.L2NpcTemplate;
import com.l2jserver.util.Rnd;

import javolution.util.FastList;
import ai.group_template.L2AttackableAIScript;

/**
 * Ice Fairy Sirra AI
 * @author Kerberos
 */

public class IceFairySirra extends L2AttackableAIScript
{
	//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<L2Npc>();
	protected Future<?> _onDeadEventTask = null;

	public IceFairySirra(int id,String name,String descr)
	{
		super(id,name,descr);
		int[] mob = {STEWARD, 22100, 22102, 22104, 29056};
		this.registerMobs(mob);
		this.addEventId(STEWARD, Quest.QuestEventType.QUEST_START);
		this.addEventId(STEWARD, Quest.QuestEventType.ON_TALK);
		this.addEventId(STEWARD, Quest.QuestEventType.ON_FIRST_TALK);
		this.addEventId(SIRRA, Quest.QuestEventType.ON_KILL);
		String test = loadGlobalQuestVar("Sirra_Respawn");
		if (!test.isEmpty())
		{
			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.setZoneEnabled(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)
	{
		L2Npc npc = null;
		for (L2Spawn spawn : SpawnTable.getInstance().getSpawnTable().values())
		{
			if (spawn != null && spawn.getNpcid() == npcId)
			{
				npc = spawn.getLastSpawn();
				break;
			}
		}
		return npc;
	}

	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().getPartyMembers())
			{
				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().getPartyMembers())
			{
				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().getPartyMembers())
			{
			//	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, String text, int time)
	{
		if (player.getParty() != null)
		{
			for (L2PcInstance pc : player.getParty().getPartyMembers())
			{
				pc.sendPacket(new ExShowScreenMessage(text,time));
			}
		}
		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.setLocx(mobs[i][1]);
					spawnDat.setLocy(mobs[i][2]);
					spawnDat.setLocz(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 );
	}

	public String onFirstTalk (L2Npc npc, L2PcInstance player)
	{
		if (player.getQuestState("IceFairySirra") == null)
			newQuestState(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;
	}

	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);	//-[JOJO]
			else
			{
				String filename;
				if (player.isInParty() && player.getParty().getPartyLeaderOID() == 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,"執事: ちょっと待って下さい。",100000);
					//	screenMessage(player,"Steward: Please wait a moment.",100000);
						filename = getHtmlPath(3);
						_sirrasZone.broadcastPacket(new CreatureSay(0, 0, npc.getName(), "公開時間は終了しました。城にいる方々は速やかに外へ出てください。"));
					}
					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.setZoneEnabled(true);
			closeGates();
			doSpawns();
			startQuestTimer("Party_Port",2000,null,player);
			startQuestTimer("End",1802000,null,player);
		}
		else if (event == "Party_Port")
		{
			teleportInside(player);
			screenMessage(player,"執事: 女王様をどうか元の姿に．．．",10000);
		//	screenMessage(player,"Steward: Please restore the Queen's appearance!",10000);
			startQuestTimer("30MinutesRemaining",300000,null,player);
		}
		else if (event == "30MinutesRemaining")
		{
			screenMessage(player,"残り30分です。",10000);
		//	screenMessage(player,"30 minute(s) are remaining.",10000);
			startQuestTimer("20minutesremaining",600000,null,player);
		}
		else if (event == "20MinutesRemaining")
		{
			screenMessage(player,"残り20分です。",10000);
		//	screenMessage(player,"20 minute(s) are remaining.",10000);
			startQuestTimer("10minutesremaining",600000,null,player);
		}
		else if (event == "10MinutesRemaining")
		{
			screenMessage(player,"執事: 時間がありません。急いでください。",10000);
		//	screenMessage(player,"Steward: Waste no time! Please hurry!",10000);
		}
		else if (event == "End")
		{
			screenMessage(player,"執事: やはり無理だったのか．．．",10000);
		//	screenMessage(player,"Steward: Was it indeed too much to ask.",10000);
			cleanUp();
		}
		else if (event == "respawn")
		{
			cleanUp();
		}
		return super.onAdvEvent(event, npc, player);
	}

	public String onKill (L2Npc npc, L2PcInstance killer, boolean isPet) 
	{
		if (npc.getNpcId() == 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();
					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 = Rnd.get(respawnMinDelay,respawnMaxDelay);
			saveGlobalQuestVar("Sirra_Respawn", String.valueOf(System.currentTimeMillis()+respawn_delay));
			startQuestTimer("respawn", respawn_delay, null, null);
		//	screenMessage(killer,"Steward: Thank you for restoring the Queen's appearance!",10000);
			screenMessage(killer,"フレヤ: ここはどこ．．．？あの日から．．．",10000);
//保留		startQuestTimer("Win",30000,null, _player);
		}
//		else if (npc.getNpcId() == 29060 /*アイス クイーンの親衛隊長*/)
//		{
//			//TODO:
//		}
		return super.onKill(npc,killer,isPet);
	}

//(未整理)"フレヤ ベアー: 攻撃だ！攻撃！"
//(未整理)"フレヤ ベアー: 命令に従います。"
//(未整理)"フレヤ ベアー: 命令に従います。"
//(未整理)"フレヤ ベアー: 命令に従います。"

//	@Deprecated
//	private void TRACE(String text) //+[JOJO]
//	{
//		_sirrasZone.broadcastPacket(new CreatureSay(0, 2, "", text));
//	}

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