/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.19
 * Generated at: 2012-12-23 21:10:23 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp.addons.Faction_0020Icons;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.sql.*;
import java.util.zip.*;
import java.util.List;
import org.apache.commons.fileupload.*;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.image.*;
import java.io.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  static {
    _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1);
    _jspx_dependants.put("/addons/Faction Icons/../../WEB-INF/.pwadminconf.jsp", Long.valueOf(1356261856000L));
  }

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write('\n');
      out.write('\n');

//-------------------------------------------------------------------------------------------------------------------------
//------------------------------- SETTINGS --------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------

	// pwadmin access password as md5 encrypted string
	// default password is root -> 63a9f0ea7bb98050796b649e85481845
	String iweb_password = "f67e209e9b8164dcb6812b9ac4357ed1";

	// connection settings to the mysql pw database
	String db_host = "localhost";
	String db_port = "3306";
	String db_user = "root";
	String db_password = "1011";
	String db_database = "pw";

	// Type of your items database required for mapping id's to names
	// Options are my or pwi
	String item_labels = "pwi";

	// Absolute path to your PW-Server main directory (startscript, stopscript, /gamed)
	// requires a tailing slash
	String pw_server_path = "/root/";

	// If you have hundreds of characters or heavy web acces through this site
	// It is recommend to turn the realtime character list feature off (false)
	// to prevent server from overload injected by character list generation
	boolean enable_character_list = true;

	String pw_server_name = "Your PW Servername";
	String pw_server_description = "+ Your server description here<br>+ 2 x 2.4 GHz, 2048 MB RAM, 100 MBit LAN<br>+ all dungeons open<br>+ tideborn nirvana weapons<br>+ World bosses";

//-------------------------------------------------------------------------------------------------------------------------
//----------------------------- END SETTINGS ------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------

	String pw_server_exp = "?";
	String pw_server_sp = "?";
	String pw_server_drop = "?";
	String pw_server_coins = "?";

	BufferedReader bfr = new BufferedReader(new FileReader(pw_server_path + "gamed/ptemplate.conf"));

	String row;
	while((row = bfr.readLine()) != null)
	{
		row = row.replaceAll("\\s", "");
		if(row.indexOf("exp_bonus=") != -1)
		{
			int pos = row.length();
			if(row.indexOf("#") != -1)
			{
				pos = row.indexOf("#");
			}
			pw_server_exp = row.substring(10, pos);
		}
		if(row.indexOf("sp_bonus=") != -1)
		{
			int pos = row.length();
			if(row.indexOf("#") != -1)
			{
				pos = row.indexOf("#");
			}
			pw_server_sp = row.substring(9, pos);
		}
		if(row.indexOf("drop_bonus=") != -1)
		{
			int pos = row.length();
			if(row.indexOf("#") != -1)
			{
				pos = row.indexOf("#");
			}
			pw_server_drop = row.substring(11, pos);
		}
		if(row.indexOf("money_bonus=") != -1)
		{
			int pos = row.length();
			if(row.indexOf("#") != -1)
			{
				pos = row.indexOf("#");
			}
			pw_server_coins = row.substring(12, pos);
		}
	}

	bfr.close();

	if(request.getSession().getAttribute("items") == null)
	{
		String[] items = new String[30001];

		try
		{
			bfr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(request.getRealPath("/include/items") + "/default.dat")), "UTF8"));
			if(item_labels.compareTo("my") == 0)
			{
				bfr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(request.getRealPath("/include/items") + "/my.dat")), "UTF8"));
			}
			if(item_labels.compareTo("pwi") == 0)
			{
				bfr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(request.getRealPath("/include/items") + "/pwi.dat")), "UTF8"));
			}
			int count = 0;
			while((row = bfr.readLine()) != null && count < 30001)
			{
				items[count] = row;
				count++;
			}
			bfr.close();
		}
		catch(Exception e)
		{
		}

		request.getSession().setAttribute("items", items);
	}

      out.write('\n');
      out.write('\n');
      out.write('\n');

	boolean admin_mode = false;

	if(request.getSession().getAttribute("ssid") != null)
	{
		admin_mode = true;
	}

      out.write("\n");
      out.write("\n");
      out.write("<html>\n");
      out.write("\n");
      out.write("<head>\n");
      out.write("\t<link rel=\"shortcut icon\" href=\"../../include/fav.ico\">\n");
      out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"../../include/style.css\">\n");
      out.write("\n");
      out.write("\t<script type=\"text/javascript\" language=\"JavaScript\">\n");
      out.write("\n");
      out.write("\t\tvar icon = new Image();\n");
      out.write("\n");
      out.write("\t\tfunction changeIcon()\n");
      out.write("\t\t{\n");
      out.write("    \t\t\ticon.src = \"icons/1_\" + document.forms[\"changeicon\"].factionid.value + \".gif\" + \"?\" + (new Date()).getTime();\n");
      out.write("\t\t\tdocument.icon.src = icon.src;\n");
      out.write("\t\t}\n");
      out.write("\n");
      out.write("\t\tfunction errorIcon()\n");
      out.write("\t\t{\n");
      out.write("    \t\t\ticon.src = \"icons/0_0.gif\" + \"?\" + (new Date()).getTime();\n");
      out.write("\t\t\tdocument.icon.src = icon.src;\n");
      out.write("\t\t}\n");
      out.write("\n");
      out.write("\t</script>\n");
      out.write("</head>\n");
      out.write("\n");
      out.write("<body>\n");
      out.write("\n");
      out.write("<table align=\"center\" width=\"400\" cellpadding=\"2\" cellspacing=\"0\" style=\"border: 1px solid #cccccc;\">\n");
      out.write("\n");
      out.write("\t<tr>\n");
      out.write("\t\t<th align=\"center\" style=\"padding: 5;\">\n");
      out.write("\t\t\t<b>FACTION ICON MANAGER</b>\n");
      out.write("\t\t</th>\n");
      out.write("\t</tr>\n");
      out.write("\n");
      out.write("\t<tr bgcolor=\"#f0f0f0\">\n");
      out.write("\t\t<td align=\"right\">\n");
      out.write("\t\t\t");

				if(admin_mode)
				{
					out.println("<font color=\"#00cc00\"><b>Root Access: </b></font> <a href=\"index.jsp?download\">Donload</a> ");
				}
				else
				{
					pageContext.include("login.jsp");
				}
			
      out.write("\n");
      out.write("\t\t</td>\n");
      out.write("\t</tr>\n");
      out.write("\n");
      out.write("\t<tr>\n");
      out.write("\t\t<td align=\"center\" valign=\"middle\">\n");
      out.write("\t\t\t");

				if(admin_mode && request.getParameter("download") != null)
				{
					String basePath = request.getRealPath(request.getServletPath().replaceAll("index.jsp", ""));

					File[] imageFiles = (new File(basePath + "/icons")).listFiles();

					int tile = 1;
					while(imageFiles.length > tile*tile)
					{
						tile = 2*tile;
					}

					BufferedImage iconlist = new BufferedImage(tile*16, tile*16, BufferedImage.TYPE_4BYTE_ABGR);
					Graphics2D iconGraphics = iconlist.createGraphics();
					BufferedWriter bw = new BufferedWriter(new FileWriter(basePath + "/iconlist_guild.txt"));
					bw.write("16\r\n");
					bw.write("16\r\n");
					bw.write(tile + "\r\n");
					bw.write(tile + "\r\n");

					BufferedImage bimg;
					int imageCount = 0;
					int tileX = 0;
					int tileY = 0;
					for(int i=0; i<imageFiles.length; i++)
					{
						if(imageFiles[i].getName().endsWith(".gif"))
						{
							bw.write(imageFiles[i].getName().replaceAll(".gif", ".dds") + "\r\n");
							bimg = ImageIO.read(imageFiles[i]);
							tileX = imageCount%tile;
							tileY = imageCount/tile;
							iconGraphics.drawImage(bimg, tileX*16, tileY*16, null);
							imageCount++;
						}
					}

					bw.close();
					iconGraphics.dispose();
					ImageIO.write(iconlist, "png", new File(basePath + "/iconlist_guild.png"));

					String[] zfiles = new String[]{"iconlist_guild.txt", "iconlist_guild.png"};
					ZipOutputStream z_out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(basePath + "/iconlist_guild.zip")));
					byte[] buffer = new byte[1024];               
					for(int i=0; i<zfiles.length; i++)
					{
						BufferedInputStream z_in = new BufferedInputStream(new FileInputStream(basePath + "/" + zfiles[i]));
						z_out.putNextEntry(new ZipEntry(zfiles[i]));
						int bcount;
						while((bcount = z_in.read(buffer, 0, buffer.length)) != -1)
						{      
							z_out.write(buffer, 0, bcount);
						}
						z_in.close();
						(new File(basePath + "/" + zfiles[i])).delete();
					}
					z_out.flush();
					z_out.close();

					// Redirect to download file
					response.sendRedirect("iconlist_guild.zip"); 
				}

				if(admin_mode || request.getSession().getAttribute("user") != null)
				{
					int uid = 0;
					if(request.getSession().getAttribute("user") != null)
					{
						uid = Integer.parseInt((String)request.getSession().getAttribute("user"));
					}

					int factionid = 0;
					Boolean delete = false;
					byte[] icon = new byte[0];

					if(request.getContentType() != null && request.getContentType().indexOf("multipart/form-data") > -1)
					{
						List items = (new org.apache.commons.fileupload.servlet.ServletFileUpload(new org.apache.commons.fileupload.disk.DiskFileItemFactory())).parseRequest(request);
                
						for(int i=0; i< items.size(); i++)
						{
							FileItem item = (FileItem)items.get(i);
							if(item.isFormField())
							{
								if(item.getFieldName().equals("factionid"))
								{
									factionid = Integer.parseInt(item.getString());
								}
								if(item.getFieldName().equals("delete"))
								{
									delete = true;
								}
							}
							else
							{
								icon = new byte[(int)item.getSize()];
								item.getInputStream().read(icon, 0, icon.length);
							}
                        			}
					}

					Class.forName("com.mysql.jdbc.Driver").newInstance();
					Connection connection = DriverManager.getConnection("jdbc:mysql://" + db_host + ":" + db_port + "/" + db_database, db_user, db_password);
					Statement statement = connection.createStatement();
					ResultSet rs;

					if(factionid > 0)
					{
						rs = statement.executeQuery("SELECT account_id FROM roles WHERE faction_id=" + factionid + " AND role_faction_rank=2");
						if(rs.next())
						{
							if(admin_mode || rs.getInt("account_id") == uid)
							{
								String iconFile = request.getRealPath(request.getServletPath().replaceAll("index.jsp", "")) + "/icons/1_" + factionid + ".gif";

								if(delete)
								{
									try
									{
										(new File(iconFile)).delete();
										out.print("<font color=\"#00cc00\"><b>Icon Removed</b></font>");
									}
									catch(Exception e)
									{
										out.print("<font color=\"#ff0000\"><b>Removing Icon Failed!</b></font>");
									}
								}
								else
								{
									if(icon.length > 0 && icon[0] == 'G' && icon[1] == 'I' && icon[2] == 'F' && icon[6] == 16 && icon[8] == 16)
									{
										FileOutputStream fos = new FileOutputStream(iconFile);
										fos.write(icon);
										fos.close();
										out.print("<font color=\"#00cc00\"><b>Icon Committed</b></font>");
									}
									else
									{
										out.print("<font color=\"#ee0000\"><b>Required Image GIF 16x16!</b></font>");
									}
								}
							}
							else
							{
								out.print("<font color=\"#ee0000\"><b>No Permissions for this Operation!</b></font>");
							}
						}
						else
						{
							out.print("<font color=\"#ee0000\"><b>Faction not Found!</b></font>");
						}
					}

					if(admin_mode)
					{
						rs = statement.executeQuery("SELECT role_name, faction_id FROM roles WHERE role_faction_rank=2");
					}
					else
					{
						rs = statement.executeQuery("SELECT role_name, faction_id FROM roles WHERE account_id=" + uid + " AND role_faction_rank=2");
					}

					out.println("<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">");
					out.println("<form name=\"changeicon\" action=\"index.jsp\" method=\"post\" enctype=\"multipart/form-data\">");
					out.println("<tr><td><font color=\"#000000\"><b>Faction (Leader): </b></font></td><td><select name=\"factionid\" onchange=\"changeIcon();\" style=\"width: 100%; text-align: left;\">");

					while(rs.next())
					{
						if(factionid == 0)
						{
							factionid = rs.getInt("faction_id");
						}

						String label = rs.getString("role_name");
						if(admin_mode)
						{
							label = "FID: " + rs.getString("faction_id") + " (" + label + ")";
						}

						if(factionid == rs.getInt("faction_id"))
						{
							out.println("<option value=\"" + rs.getString("faction_id") + "\" selected>" + label + "</option>");
						}
						else
						{
							out.println("<option value=\"" + rs.getString("faction_id") + "\">" + label + "</option>");
						}
					}

					rs.close();
					connection.close();

					out.println("</select></td></tr>");

					out.println("<tr><td><font color=\"#000000\"><b>Current Icon: </b></font></td><td><img name=\"icon\" onerror=\"errorIcon();\"></img></td></tr>");
					out.println("<tr><td><font color=\"#000000\"><b>Reset Icon: </b></font></td><td><input type=\"checkbox\" name=\"delete\" value=\"true\"></input></td></tr>");
					out.println("<tr><td><font color=\"#000000\"><b>Commit Icon: </b></font></td><td><input type=\"file\" name=\"icon\"></input></td></tr>");
					out.println("<tr><td align=\"center\" colspan=\"2\"><input type=\"image\" src=\"../../include/btn_submit.jpg\" style=\"border: 0px; vertical-align: middle;\"></input></td></tr>");
					out.println("</form>");
					out.println("</table>");
				}
				else
				{
					out.println("<font color=\"#ee0000\"><b>Access Denied!</b></font>");
				}
			
      out.write("\n");
      out.write("\t\t</td>\n");
      out.write("\t</tr>\n");
      out.write("\n");
      out.write("</table>\n");
      out.write("\n");
      out.write("<script>\n");
      out.write("\twindow.onload = changeIcon; \n");
      out.write("</script>\n");
      out.write("\n");
      out.write("</body>\n");
      out.write("\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
