package org.chenyang.http.impl.cookie;

import org.chenyang.http.annotation.Contract;
import org.chenyang.http.annotation.ThreadingBehavior;
import org.chenyang.http.cookie.CommonCookieAttributeHandler;
import org.chenyang.http.cookie.MalformedCookieException;
import org.chenyang.http.cookie.SetCookie;
import org.chenyang.http.util.Args;
import org.chenyang.http.client.utils.DateUtils;

import java.util.Date;

@Contract(
   threading = ThreadingBehavior.IMMUTABLE
)
public class BasicExpiresHandler extends AbstractCookieAttributeHandler implements CommonCookieAttributeHandler {
   private final String[] datePatterns;

   public BasicExpiresHandler(String[] datePatterns) {
      Args.notNull(datePatterns, "Array of date patterns");
      this.datePatterns = datePatterns.clone();
   }

   public void parse(SetCookie cookie, String value) throws MalformedCookieException {
      Args.notNull(cookie, "Cookie");
      if (value == null) {
         throw new MalformedCookieException("Missing value for 'expires' attribute");
      } else {
         Date expiry = DateUtils.parseDate(value, this.datePatterns);
         if (expiry == null) {
            throw new MalformedCookieException("Invalid 'expires' attribute: " + value);
         } else {
            cookie.setExpiryDate(expiry);
         }
      }
   }

   public String getAttributeName() {
      return "expires";
   }
}
