/*
 * 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 javolution.util.FastList;
import net.sf.l2j.gameserver.datatables.DoorTable;
import net.sf.l2j.gameserver.datatables.NpcTable;
import net.sf.l2j.gameserver.datatables.SpawnTable;
import net.sf.l2j.gameserver.instancemanager.GrandBossManager;
import net.sf.l2j.gameserver.model.L2ItemInstance;
import net.sf.l2j.gameserver.model.L2Spawn;
import net.sf.l2j.gameserver.model.actor.instance.L2DoorInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2NpcInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.model.quest.Quest;
import net.sf.l2j.gameserver.model.zone.type.L2BossZone;
import net.sf.l2j.gameserver.network.serverpackets.ActionFailed;
import net.sf.l2j.gameserver.network.serverpackets.CreatureSay;
import net.sf.l2j.gameserver.network.serverpackets.ExShowScreenMessage;
import net.sf.l2j.gameserver.network.serverpackets.NpcHtmlMessage;
import net.sf.l2j.gameserver.templates.chars.L2NpcTemplate;
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 boolean Config_SIRRA_ALONE_PLAY = false;
	private static final int SIRRA = 29056;		//シルー
	private static final int STEWARD = 32029;	//執事
	private static final int SILVER_HEMOCYTE = 8057;	//銀の血
	private static L2BossZone _freyasZone;
	private static L2PcInstance _player = null;
	protected FastList<L2NpcInstance> _allMobs = new FastList<L2NpcInstance>();
	protected Future<?> _onDeadEventTask = null;

	public IceFairySirra(int id,String name,String descr)
	{
        super(id,name,descr);
        int[] mob = {STEWARD, 22100, 22102, 22104};
        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);
        init();
	}

	public void init()
	{
		_freyasZone = GrandBossManager.getInstance().getZone(105546 , -127892 , -2768);
		if (_freyasZone == null)
		{
			_log.warning("IceFairySirraManager: Failed to load zone");
			return;
		}
		_freyasZone.setZoneEnabled(false);
		findTemplate(STEWARD).setBusy(false);
		openGates();
	}

	public void cleanUp()
	{
		init();
		cancelQuestTimer("30MinutesRemaining",null, _player);
		cancelQuestTimer("20MinutesRemaining",null, _player);
		cancelQuestTimer("10MinutesRemaining",null, _player);
		cancelQuestTimer("End",null, _player);
		for (L2NpcInstance mob : _allMobs)
		{
			try
			{
				mob.getSpawn().stopRespawn();
				mob.deleteMe();
			}
			catch (Exception e)
			{
			    _log.log(Level.SEVERE, "IceFairySirraManager: Failed deleting mob.", e);
			}
		}
		_allMobs.clear();
	}

	public L2NpcInstance findTemplate(int npcId)
	{
		L2NpcInstance 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 if (Config_SIRRA_ALONE_PLAY)
		{
			L2ItemInstance i = player.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 if (Config_SIRRA_ALONE_PLAY)
		{
			L2ItemInstance i = player.getInventory().getItemByItemId(SILVER_HEMOCYTE);
			player.destroyItem("Hemocytes", i.getObjectId(), 1, 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 (_freyasZone == null)
				{
					_log.warning("IceFairySirraManager: Failed to load zone");
					cleanUp();
					return;
				}
				_freyasZone.allowPlayerEntry(pc,2103);
			}
		}
		else if (Config_SIRRA_ALONE_PLAY)
		{
			player.teleToLocation(113533,-126159,-3488,false);
			_freyasZone.allowPlayerEntry(player,2103);
		}
		else
			cleanUp();
	}
	public void screenMessage(L2PcInstance player, String text, int time)
	{
		if (player.getParty() != null)
		{
			player.getParty().broadcastToPartyMembers(new ExShowScreenMessage(text,time));	//+[JOJO]
//			for (L2PcInstance pc : player.getParty().getPartyMembers())						//-[JOJO]
//			{
//				pc.sendPacket(new ExShowScreenMessage(text,time));
//			}
		}
		else if (Config_SIRRA_ALONE_PLAY)
			player.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(L2NpcInstance npc, L2PcInstance player, String filename)
	{
		NpcHtmlMessage html = new NpcHtmlMessage(npc.getObjectId());
        html.setFile(filename);
        html.replace("%objectId%", String.valueOf(npc.getObjectId()));
        player.sendPacket(html);
        player.sendPacket( ActionFailed.STATIC_PACKET );
	}

	public String onFirstTalk (L2NpcInstance 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, L2NpcInstance npc, L2PcInstance player)
	{
		if (event.equals/*IgnoreCase*/("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() || Config_SIRRA_ALONE_PLAY)
				{
					if (checkItems(player) == true)
					{
						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);
						if (_freyasZone == null) init();
						_freyasZone.broadcastPacket(new CreatureSay(0, 0, npc.getName(), "公開時間は終了しました。城にいる方々は速やかに外へ出てください。"));
					//	_freyasZone.broadcastPacket(new ExShowScreenMessage("公開時間は終了しました。城にいる方々は速やかに外へ出てください。",/*time=>*/10000));
					}
					else
					{
						filename = getHtmlPath(2);
					}
				}
				else
				{
					filename = getHtmlPath(1);
				}
				sendHtml(npc, player, filename);
			}
        }
		else if (event == "start")
        {
			if (_freyasZone == null)
			{
				_log.warning("IceFairySirraManager: Failed to load zone");
				cleanUp();
				return super.onAdvEvent(event, npc, player);
			}
			_freyasZone.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 == "Win")
		{
			for (L2NpcInstance mob : _allMobs)
				mob.deleteMe();
		//	openGates();
			startQuestTimer("cleanUp",300000,null,null);
		}
		else if (event == "cleanUp")
		{
			cleanUp();
		}
		return super.onAdvEvent(event, npc, player);
	}

	public String onKill (L2NpcInstance npc, L2PcInstance killer, boolean isPet)	//+[JOJO]
	{
		int npcId = npc.getNpcId();
		if (npcId == SIRRA)
		{
			cancelQuestTimer("30MinutesRemaining",null, _player);
			cancelQuestTimer("20MinutesRemaining",null, _player);
			cancelQuestTimer("10MinutesRemaining",null, _player);
			cancelQuestTimer("End",null, _player);
			
			screenMessage(killer,"フレヤ: ここはどこ．．．？あの日から．．．",10000);
			startQuestTimer("Win",30000,null, _player);
		}
//		else if (npcId == 29060 /*アイス クイーンの親衛隊長*/)
//		{
//			//TODO:
//		}
		return super.onKill(npc,killer,isPet);
	}

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

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

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