package dk.zqz.blojsom.plugins.filetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.blojsom.blog.BlogEntry;
import org.blojsom.blog.FileBackedBlogEntry;
import org.blojsom.util.BlojsomUtils;

/**
 * @author: Lars Chr. Hausmann <jazz@zqz.dk>
 * @version $Revision: 1.3 $ $Date: 2004/01/18 20:01:49 $ 
 * 
 * Create a comparator, which will try to look for file names ending in :
 * <Titlte>-<date>.txt, where <date> is of the format:
 * "yyyy-MM-dd-hh=mm"
 * 
 * If that can not be found, use the lastModified time of the entry.
 *
 * slight modification to account for single blog entry
 * made by Jay Fienberg, April 9, 2004 
 */
 
public class FileTimeComparator implements Comparator {
  private static Pattern p = Pattern.compile("^.*(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.[\\w]+$");
  private static SimpleDateFormat fileFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm");
  private static SimpleDateFormat metaFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
  private static Calendar calendar = new GregorianCalendar();
  private static final String METADATA_ENTRY_DATE_KEY = "entry-date";
    
  
  /**
   * Compare object 1 with object 2.
   */
  public int compare(Object o1, Object o2) {
    int retVal = 0;
    BlogEntry b1 = null;
    BlogEntry b2 = null;
    
    if (o1 instanceof BlogEntry) {
      b1 = (BlogEntry) o1;
    }
    
    if (o2 instanceof BlogEntry) 
      b2 = (BlogEntry) o2;
    
    long l1 = getDate(b1);
    long l2 = getDate(b2);
    
    if (l1 < l2)
      retVal = 1;
    if (l1 == l2)
      retVal = 0;
    if (l1 > l2)
      retVal = -1;
    
    return retVal;
  }

   
  /**
   * Return the date as a long, in milliseconds,
   * 
   * @param b The entry to find the date for.
   * @return the date in milliseconds.
   */
  protected long getDate(BlogEntry b) {
    long retVal = 0;

    Date date = null;
        
    if (BlojsomUtils.checkMapForKey(b.getMetaData(),METADATA_ENTRY_DATE_KEY)) {
       Map meta = b.getMetaData();
       String stringDate = (String) meta.get(METADATA_ENTRY_DATE_KEY);
       try {
        date = metaFormat.parse(stringDate);
      } catch (ParseException e) {
        // Sit on it 
      }

    } else if (b instanceof FileBackedBlogEntry) {
        String filename = ((FileBackedBlogEntry)b).getSource().getName(); 
      
        Matcher m = p.matcher(filename);
        boolean foundDate = m.find();
        
        if (foundDate) {
          try {
            // Extract the date. 
            date = fileFormat.parse(m.group(1));
          } catch (ParseException e) {
            // Sit on it
          }
        }
    } 
      
    
    if (date != null) {
      calendar.clear();
      calendar.setTime(date);
      b.setDate(date);
      
      retVal = calendar.getTimeInMillis();
    } else {
      retVal =b.getLastModified();
    }
    return retVal;
  }
}
