/*
 * NmailUtility.java
 * 
 * Created on 2007.09.26., 23:37:25
 * 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.nir.nmail.utils;

import hu.nir.nmail.ejb.entity.EmailSendingProces;
import hu.nir.nmail.ejb.entity.NmailUser;
import hu.nir.nmail.ejb.entity.SmtpSettings;
import hu.nir.nmail.ejb.entity.UserSetting;
import hu.nir.nmail.ejb.stateless.UserProcesManager;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Fodor Attila
 */
public class NmailUtility {
    private static Logger log = Logger.getLogger(NmailUtility.class.getName());
    
    @SuppressWarnings("unchecked")
    public static Map toMap(Object key, Object value) {
        Map map = new HashMap();
        map.put(key, value);
        return map;
    }
    
    @SuppressWarnings("unchecked")
    public static Map toMap(Object key1,Object value1, Object key2, Object value2) {
        Map map = new HashMap();
        map.put(key1, value1);
        map.put(key2, value2);
        return map;
    }
    
    @SuppressWarnings("unchecked")
    public static Map toMap(Object key1,Object value1, Object key2, Object value2, Object key3, Object value3) {
        Map map = new HashMap();
        map.put(key1, value1);
        map.put(key2, value2);
        map.put(key3, value3);
        return map;
    }
    
    public static Properties getSMTPProperties(SmtpSettings smtpSettings) {
        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", smtpSettings.getSmtpSettingsPK().getHost());
        properties.put("mail.transport.protocol", smtpSettings.getProtocol());
        properties.put("mail.debug", String.valueOf(smtpSettings.getDebug()));
        properties.put("mail.smtp.port", String.valueOf(smtpSettings.getPort()));
        properties.put("mail.smtp.starttls.enable", String.valueOf(smtpSettings.getTls()));
        properties.put("mail.smtp.auth", String.valueOf(smtpSettings.getAuth()));
        properties.put("mail.user", smtpSettings.getSmtpSettingsPK().getSmtpUserName());
        properties.put("mail.password", smtpSettings.getSmtpPassword());
        return properties;
    }
    
    @SuppressWarnings("unchecked")
    public static Map mergeMaps(Map... maps) {
        Map returnMap = new HashMap();
        
        for (Map map : maps) {
            
            if (map == null) {
                continue;
            }
            
            Set keySet = map.keySet();
            
            for (Object key : keySet) {
                Object value = map.get(key);
                
                if (returnMap.containsKey(key) && value instanceof List) {
                    value = mergeLists((List) returnMap.get(key), (List) value);
                }
                else if (returnMap.containsKey(key) && value instanceof Map) {
                    value = mergeMaps((Map) returnMap.get(key), (Map) value);
                }
                
                returnMap.put(key, value);
            }
        }
        
        return returnMap;
    }
    
    @SuppressWarnings("unchecked")
    public static List mergeLists(List... lists) {
        List returnList = new ArrayList();
        
        for (List list : lists) {
            for(Object o : list) {
                returnList.add(o);
            }
        }
        
        return returnList;
    }
    
    /**
     * Convert isoString to UTF-8, and mimeencoding it, if it passible.
     * @param isoString
     * @return
     */
    public static String toUTF8(String isoString) {
        String utf8String = null;
        
        if (null != isoString && !isoString.equals("")) {
        
            try {
                byte[] stringBytesISO = isoString.getBytes("ISO-8859-1");
                utf8String = new String(stringBytesISO, "UTF-8");
            }
            catch (UnsupportedEncodingException e) {
                // As we can't translate just send back the best guess.
                utf8String = isoString;
                log.log(Level.WARNING, "String encoding conversion to UTF-8 wasn't successful so we use the isoString.");
            }
        }
        else {
           utf8String = isoString;
        }
        
        return utf8String;
    }
    
    public static String encodeText(String string) {
        try {
            string = toUTF8(string);
            string = MimeUtility.encodeText(string, "UTF-8", null);
        } catch (UnsupportedEncodingException ex) {
            log.log(Level.WARNING, "Can't encode text.");
        }
        return string;
    }
    
    public static File getMboxFile(NmailUser nmailUser) {
        Properties props = System.getProperties();
        File mboxFile = new File(props.getProperty("java.io.tmpdir") + File.separator + nmailUser.getNmailUserLogin().getUserName()+".nmail");
        return mboxFile;
    }
    
    public static boolean hasSendingRight(NmailUser nmailUser, UserProcesManager userProcesManager) {
        EmailSendingProces notFinishedUserProcess = userProcesManager.getNotFinishedEmailSendingProceses(nmailUser);
        
        if (notFinishedUserProcess != null) {
            return false;
        }
        
        if (isTimeRestricted(nmailUser, userProcesManager)) {
            return false;
        }
        
        return true;
    }
    
    private static boolean isTimeRestricted(NmailUser nmailUser, UserProcesManager userProcesManager) {
        UserSetting userSettings = nmailUser.getUserSetting();
        Date now = new Date();
        BigInteger timeLimit = userSettings.getTimeLimit();
        
        if (timeLimit == null) {
            return false;
        }
        
        EmailSendingProces lastUserProcess = userProcesManager.getLastEmailSendingProces(nmailUser);
        
        if (lastUserProcess == null) {
            return false;
        }
        
        Date lastSendDate = lastUserProcess.getStartProces();
        long nextPossibleTime = lastSendDate.getTime() + timeLimit.longValue();
        
        if (now.getTime() < nextPossibleTime) {
            return true;
        }
        
        return false;
    }
    
    public static void logRequest(HttpServletRequest request, String name) {
        Logger logger = Logger.getLogger(name);
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            logger.log(Level.INFO, request.getParameter((String) parameterNames.nextElement()));
        }
    }
}
