/*
 * 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 events.CharacterBirthday;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Calendar;

import javolution.lang.MathLib;

import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.datatables.SkillTable;
import com.l2jserver.gameserver.handler.UserCommandHandler;
import com.l2jserver.gameserver.instancemanager.QuestManager;
import com.l2jserver.gameserver.model.L2Skill;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
import com.l2jserver.gameserver.model.quest.State;
import com.l2jserver.gameserver.network.serverpackets.MagicSkillUse;
import com.l2jserver.gameserver.network.serverpackets.PlaySound;

/**
 * @author Gnacik
 * 
 */

public class CharacterBirthday extends Quest
{
	private static final int _npc = 32600;
	private static boolean is_spawned = false;
	
	private final static int[] _gk =
	{
		30006,30059,30080,30134,30146,30177,30233,30256,30320,30540,
		30576,30836,30848,30878,30899,31275,31320,31964,32163
	};

	public CharacterBirthday(int questId, String name, String descr)
	{
		super(questId, name, descr);
		addStartNpc(_npc);
		addFirstTalkId(_npc);
		addTalkId(_npc);
		for (int id : _gk)
		{
			addStartNpc(id);
			addTalkId(id);
		}
	}

	public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
	{
		String htmltext = "";
		QuestState st = player.getQuestState(getName());
		htmltext = event;

		if (event.equalsIgnoreCase("despawn_npc"))
		{
			npc.doDie(player);
			is_spawned = false;

			htmltext = null;
		}
		else if (event.equalsIgnoreCase("receive_reward"))
		{
			if (player.checkBirthDay() == 0)
			{
				// Give Adventurer Hat (Event)
				st.giveItems(10250, 1);
	
				// Give Buff			
				L2Skill skill;
				skill = SkillTable.getInstance().getInfo(5950, 1);
				if (skill != null)
					skill.getEffects(npc, player);
				npc.setTarget(player);
				npc.broadcastPacket(new MagicSkillUse(player, 5950, 1, 1000, 0));
	
				// Despawn npc
				npc.doDie(player);
				is_spawned = false;
	
				// Update for next year
				Calendar now = Calendar.getInstance();
				now.setTimeInMillis(System.currentTimeMillis());
				st.set("Birthday", String.valueOf(now.get(Calendar.YEAR)+1));
				st.setState(State.STARTED);	//[JOJO] checkBirthDay() 用ダミー
	
				htmltext = "32600-ok.htm";
			}
			else if (player.checkBirthDayA() == 0)
				htmltext = "32600-already.htm";
			else
				htmltext = "32600-no.htm";
		}
		//[JOJO]-------------------------------------------------
		else if (event.startsWith("set_birthday "))
		{
			if (player.getCreateTime() == 0)
			{
				Calendar cal;
				try
				{
					String[] d = event.split(" ");
					int year = 2000 + Integer.parseInt(d[1]);
					int month = Integer.parseInt(d[2]);
					int date = Integer.parseInt(d[3]);
					
					cal = Calendar.getInstance();
					cal.setLenient(false); // strictly
					cal.set(year, month - 1, date, 0,0,0);
					cal.getTimeInMillis();	// if NOT valid then throw IllegalArgumentException.
					
					Calendar test = Calendar.getInstance();
					test.set(test.get(Calendar.YEAR), test.get(Calendar.MONTH), test.get(Calendar.DATE), 0,0,0);	// Today 00:00:00
					if (cal.compareTo(test) >= 0)
						throw new IllegalArgumentException();
					
					test.set(2004, 6 - 1, 25, 0,0,0);	// Lineage II epoch day
					if (cal.compareTo(test) < 0)
						throw new IllegalArgumentException();
				}
				catch (IllegalArgumentException e)
				{
					player.sendMessage("無効な日付です。");
					return "set_birthday.htm";
				}
				catch (Exception e)
				{
					e.printStackTrace();
					return "";
				}
				
				player.setCreateTime(cal.getTimeInMillis());
				updateDbCreateTime(player);
			}
			/* 126: data/scripts/handlers/usercommandhandlers/Birthday.java */
			UserCommandHandler.getInstance().getUserCommandHandler(126).useUserCommand(126, player);
			return "";
		}
		//-------------------------------------------------------
		return htmltext;
	}

	public String onTalk(L2Npc npc, L2PcInstance player)
	{
		//[JOJO]-------------------------------------------------
		if (player.getCreateTime() == 0) // 古参キャラは誕生日が無い
			return "set_birthday.htm";
		//-------------------------------------------------------

		if(is_spawned)
			return null;

		QuestState st = player.getQuestState(getName());
		if (st == null)
		{
			Quest q = QuestManager.getInstance().getQuest(getName());
			st = q.newQuestState(player);
		}
		if (/*st != null &&*/ player.checkBirthDay() == 0)
		{
			player.sendPacket(new PlaySound(1, "HB01", 0, 0, 0, 0, 0));
			//[JOJO]-------------------------------------------------
			int x, y, h;
			{
				final double r = 20;
				double a = Math.atan2(npc.getY() - player.getY(), npc.getX() - player.getX()) + (MathLib.TWO_PI / 8);
				x = player.getX() + (int)(r * Math.cos(a));
				y = player.getY() + (int)(r * Math.sin(a));
				h = (int)((a + Math.PI) * (65536.0 / MathLib.TWO_PI)) % 65536;
			}
			L2Npc spawned = st.addSpawn(32600, x, y, player.getZ()+10, h, false, 0, true);
		//	st.setState(State.STARTED);	//-[JOJO] "receive_reward" に移動
			//-------------------------------------------------------
			st.startQuestTimer("despawn_npc", 60000, spawned);
			is_spawned = true;
		}
		else if (player.checkBirthDayA() == 0)
			return "32600-already.htm";
		else
			return "32600-no.htm";

		return null;
	}

	public String onFirstTalk(L2Npc npc, L2PcInstance player)
	{
		String htmltext = "";
		QuestState st = player.getQuestState(getName());
		if (st == null)
		{
			Quest q = QuestManager.getInstance().getQuest(getName());
			st = q.newQuestState(player);
		}
		if (player.checkBirthDay() == 0)
			htmltext = "32600.htm";
		else if (player.checkBirthDayA() == 0)
			return "32600-already.htm";
		else
			htmltext = "32600-no.htm";
		return htmltext;
	}

	//[JOJO]-------------------------------------------------
	private boolean updateDbCreateTime(L2PcInstance player)
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE characters SET createTime=? WHERE charId=?");
			
			statement.setLong(1, player.getCreateTime());
			statement.setInt(2, player.getObjectId());
			
			statement.executeUpdate();
			statement.close();
		}
		catch (Exception e)
		{
			_log.severe("Could not update char createTime: " + e);
			return false;
		}
		finally
		{
			L2DatabaseFactory.close(con);
		}
		return true;
	}
	//-------------------------------------------------------

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