/*
 *  @author Ranides Atterwim <ranides@gmail.com>
 *  @copyright Ranides Atterwim
 *  @license WTFPL
 *  @url http://ranides.net/projects/assira
 */

package net.ranides.assira.time;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author ranides
 */
public class DateQuickFormat extends SimpleDateFormat {

    final public static String FORMAT_DATE_ISO      = "date/iso";
    final public static String FORMAT_DATE          = "date/short";
    final public static String FORMAT_DATE_LONG     = "date/long";
    final public static String FORMAT_DATE_TRACE    = "date/logger";
    final public static String FORMAT_TIME          = "time/short";
    final public static String FORMAT_TIME_LONG     = "time/long";
    final public static String FORMAT_TIME_TRACE    = "time/logger";

    private static final Map<String, String> patterns = Collections.synchronizedMap(new HashMap<String, String>());

    static {
        patterns.put(FORMAT_DATE,       "yyyy-MM-dd");
        patterns.put(FORMAT_DATE_ISO,   "yyyyMMddHHmm");
        patterns.put(FORMAT_DATE_LONG,  "yyyy-MM-dd HH:mm:ss");
        patterns.put(FORMAT_DATE_TRACE, "yyyy-MM-dd HH:mm:ss.SSS");
        patterns.put(FORMAT_TIME,       "HH:mm");
        patterns.put(FORMAT_TIME_LONG,  "HH:mm:ss");
        patterns.put(FORMAT_TIME_TRACE, "HH:mm:ss.SSS");
    }

    public DateQuickFormat(String pattern) {
        super();
        this.applyPattern( patterns.containsKey(pattern) ? patterns.get(pattern) : pattern );
    }

    public static void register(String name, String pattern) {
        patterns.put(name, pattern);
    }

    public static void unregister(String name) {
        patterns.remove(name);
    }

    public static String format(String pattern, Object time) {
        if (time instanceof Number) {
            return new DateQuickFormat(pattern).format(new Date( ((Number)time).longValue() ));
        }
        if (time instanceof Date) {
            return new DateQuickFormat(pattern).format( (Date)time );
        }
        return new DateQuickFormat(pattern).format(time);
    }

    public static String format(String pattern, Date time) {
        return new DateQuickFormat(pattern).format(time);
    }

}
