package org.chenyang.http.cookie;

import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.impl.cookie.BasicClientCookie;
import java.util.Comparator;
import java.util.Date;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class CookiePriorityComparator implements Comparator<Cookie> {
   public static final CookiePriorityComparator INSTANCE = new CookiePriorityComparator();

   private int getPathLength(Cookie cookie) {
      String path = cookie.getPath();
      return path != null ? path.length() : 1;
   }

   public int compare(Cookie c1, Cookie c2) {
      int l1 = this.getPathLength(c1);
      int l2 = this.getPathLength(c2);
      int result = l2 - l1;
      if (result == 0 && c1 instanceof BasicClientCookie && c2 instanceof BasicClientCookie) {
         Date d1 = ((BasicClientCookie)c1).getCreationDate();
         Date d2 = ((BasicClientCookie)c2).getCreationDate();
         if (d1 != null && d2 != null) {
            return (int)(d1.getTime() - d2.getTime());
         }
      }

      return result;
   }
}
