/*
 * 
 * Created on Jul 31, 2005
 * 
 * György Süveges
 * Etixpert Kft.
 * Copyright(c) 2005
 * 
 */
package com.etixpert.evolution.gui.servlets;


import java.sql.*;
import com.etixpert.evolution.*;
import com.etixpert.evolution.gui.servlets.elements.*;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.jstl.fmt.*;
import javax.servlet.*;

/**
 * @author Suveges Gyorgy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */


public class NewsletterHelper {
     
	public static String decodeEuro(String orig) throws Exception {
		StringBuffer sb = new StringBuffer(orig);
		char euro = 0x80; 
		
		boolean b = true;
		int from = 0;
		
		while (b) {
			int pos = sb.indexOf("&#8364;", from);
			if (pos!=-1) {
				from = pos+1;
				sb.replace(pos, pos+7, new String("\u20AC".getBytes(), "iso-8859-15"));
			} else b = false;
		}
		
		
		
		b = true;
		from = 0;
		
		/*while (b) {
			int pos = sb.indexOf(String.valueOf(0xA4), from);
			if (pos!=-1) {
				from = pos+1;
				sb.replace(pos, pos+1, "€");
			} else b = false;
		}*/
		
		
		return sb.toString();
	}
	
    
    public static int getRecipientHeight(Connection conn, String right, Integer levelId) throws Exception {
        if (right.equalsIgnoreCase("x")) return 0;
        else  {
            ObjectSearch os = new ObjectSearch();
            
            List l = os.search(conn, "select count(*) as num_of_roles from user_roles where id>80"+(levelId.intValue()>100?" AND id<="+levelId.intValue():""));
            PersistableObject po = (PersistableObject) l.get(0);
          
            int size = ((Long) po.get("num_of_roles")).intValue()+4;
        
            return size;
        } 
    }
    
    public static String getFrom(Connection conn, HttpSession session) throws Exception {
        Integer levelID= new Integer((String) session.getAttribute("USER_LOGGED_ID"));
        ObjectSearch os = new ObjectSearch();
        List l=os.search(conn, "select email from distributor where id=?", new Object[]{levelID});
        PersistableObject po = (PersistableObject) l.get(0);
        return po.getString("email","");
        
    }
    
    public static String getRight(Connection conn, HttpSession session) throws Exception {
        Integer levelID= new Integer((String) session.getAttribute("USER_LOGGED_LEVEL_ID"));
        ObjectSearch os = new ObjectSearch();
        List l = os.search(conn, "select newsletter from general_rights where role_id=?", new Object[] {new Integer((String) session.getAttribute("USER_LOGGED_LEVEL_ID"))});
        PersistableObject po = (PersistableObject) l.get(0);
        return (String) po.get("newsletter");
        
    }
    
    public static String generateFileList(PageContext pageContext) throws Exception {
        HttpSession session = pageContext.getSession();
      
        
    	Map jspMap = (Map) session.getAttribute("newsletter.jsp");
        if (jspMap==null) return  "";
        List fileItems = (List) jspMap.get("files");
        if (fileItems==null || fileItems.size()==0) return "";
        StringBuffer sb = new StringBuffer();
        sb.append("<table width=\"100%\">\n");
        sb.append(" <col/><col/><col width=\"50\"/>\n");
        for (int i=0; i<fileItems.size(); i++) {
            FileItem fileItem = (FileItem) fileItems.get(i);
            sb.append(" <tr>\n");
            sb.append("   <td><small>").append(new String(Tools.getFileName(fileItem.getName()).getBytes(),"ISO-8859-2")).append("</small></td>\n");
            sb.append("   <td align=\"right\"><small>").append(fileItem.getSize()).append("</small></td>\n");
            sb.append("   <td> <input type=\"button\" value=\""+LocaleSupport.getLocalizedMessage(pageContext, "DELETE")+"\" onclick=\"Del('"+i+"')\"</td>\n");
            sb.append(" </tr>");
            		
        }
        
        sb.append("</table>");
        
        return sb.toString();
        
              
            
    }
    public static String generateDownlineSelect(Connection conn, HttpSession session, String jsp, String right) throws Exception {
        List l1 = new ArrayList();
		l1.add("id");
		ObjectSearch os = new ObjectSearch("distributor",l1);
		String root ="0";
		String toSelect="st";
		boolean isAdmin = right.equalsIgnoreCase("a");
		if (!isAdmin) {
		    root = (String) session.getAttribute("USER_LOGGED_ID");
		    toSelect=right.toLowerCase();
		}
		MainControl.logger.debug("downline: "+ toSelect+"("+root+")");
		os.setCondition("id in (select * from {fn "+toSelect+"("+root+")}) and active and not deleted");
		os.setOrderBy(new String[]{"lastname","firstname"});
		QuerySelect select = new QuerySelect(session, jsp, "dist_id2", os, "id","lastname,firstname",isAdmin?"0":(String) session.getAttribute("USER_LOGGED_ID"));
		select.setConnection(conn);
		select.addProperty("onchange", "cnr_changed()");
		select.addProperty("onblur", "cnr_changed()");
		return select.toHTML();
    }
    public static String generateRoles(Connection conn, HttpSession session, String jsp) throws Exception {
        Integer levelID= new Integer((String) session.getAttribute("USER_LOGGED_LEVEL_ID"));
        StringBuffer sb = new StringBuffer();
       
        ObjectSearch os = new ObjectSearch();
        List l = os.search(conn,"select id, descr from user_roles where id>=? and id<=? order by id", new Object[]{new Integer(90), levelID.intValue()>=100?levelID:new Integer(10000)});
       
        sb.append("<td rowspan=\""+l.size()+"\" align=\"center\"><b><small>Stufen</small></b></td>");
        for (int i=0; i<l.size(); i++) {
          if (i>0) sb.append("<tr>\n");    
        
          sb.append("<td>");
          PersistableObject po = (PersistableObject) l.get(i);
          CheckBox role = new CheckBox(session, jsp, "role_id", po.getString("id",""), "<small>"+po.getString("descr", "-")+"</small>", true);
          sb.append(role.toHTML()).append("\n");
          sb.append("</tr>");
        }
        
        return sb.toString();
        
    }
}
