/*****************************************************************************
 * Copyright (C) The Apache Software Foundation. All rights reserved.        *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the Apache Software License *
 * version 1.1, a copy of which has been included  with this distribution in *
 * the LICENSE file.                                                         *
 *****************************************************************************/

package org.apache.james.util;

import java.util.*;
import java.text.*;

/**
 * I suppose I could access some of the special messages within Sun's implementation of the JavaMail
 * API, but I've always been told not to do that.  This class has one static method that takes a
 * java.util.Date object and returns a nicely formatted String version of this, formatted as per the
 * RFC822 mail date format.
 * @author Serge Knystautas <sergek@lokitech.com>
 * @version 0.9.1
 * @patched Lionel Lindemann <lionel@proliber.com>
 * p1: On a non-English system, the date string was in the system language, resulting
 * in an error in the SMTP Date field.
 * p2: On a NT/2000 system, the time was not taking into account daylight savings. I guess this 
 * was also a problem on other systems, but I couldn't check.
 */
public class RFC822DateFormat {
    private static DateFormat df;
    private static DecimalFormat tz;

    /**
     * SimpleDateFormat will handle most of this for us, but the timezone won't match, so we do that
     * manually
     * @return java.lang.String
     * @param d Date
     */
    public static String toString(Date d) {
        if (df == null) {
            // p1: added locale to avoid sending a non-English date on localized systems
            df = new SimpleDateFormat("EE, d MMM yyyy HH:mm:ss", Locale.ENGLISH);
        }
        if (tz == null) {
            tz = new DecimalFormat("00");
        }

        StringBuffer sb = new StringBuffer(df.format(d));

        sb.append(' ');
        
        // p2: Used ZONE_OFFSET + DST_OFFSET instead of getRawOffset() to take into account daylight savings
        GregorianCalendar rightNow = new GregorianCalendar();
        int min = (rightNow.get(rightNow.ZONE_OFFSET) + rightNow.get(rightNow.DST_OFFSET)) / 1000 / 60;

        if (min >= 0) {
            sb.append('+');
        } else {
            sb.append('-');
        }

        min = Math.abs(min);

        sb.append(tz.format(min / 60));
        sb.append(tz.format(min % 60));

        return sb.toString();
    }

}



/*--- formatting done in "Sun Java Convention" style on 07-11-1999 ---*/


