package edu.hawaii.ics415.problem3.fieldcheck.util;

import javax.servlet.http.Cookie;

/**
 * Provides utilities for servlet. It includes the method which is related to
 * the cookie.
 *
 * @author   Takuya Yamashita
 */
public class ServletUtility {

  /**
   * Gets the cookie attribute of the ServletUtility object
   *
   * @param cookies       An array of the cookie instance to be passed.
   * @param cookieName    An cookie name which is looked for.
   * @param defaultValue  An default value if the cookie name is not found in
   *      the array of the cookie
   * @return              The cookie value to be found or default value if the
   *      cookie name is not found.
   */
  public static String getCookie(Cookie[] cookies, String cookieName, String defaultValue) {
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];

        if (cookieName.equals(cookie.getName())) {
          return (cookie.getValue());
        }
      }
    }
    return defaultValue;
  }

  /**
   * Provids the way to get cookies. returns null if the specific cookieName is
   * not found inside the Cookie.
   *
   * @param cookies     An array of the Cookie object
   * @param cookieName  The cookie name which could be found in the Cookie
   *      object
   * @return            The cookie value which is stored in the COokie object
   */
  public static String getCookie(Cookie[] cookies, String cookieName) {
    return getCookie(cookies, cookieName, null);
  }

}