package coreservlets;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

/** Serwlet, który zmienia ofertę dnia. Deskryptor web.xml
 *  wskazuje, że jedynie uwierzytelnieni użytkownicy z rolą
 *  ceo będą mogli uruchomić serwlet. Proces nasłuchujący 
 *  atrybuty kontekstu serwletu resetuje licznik zamówień
 *  na oferty dnia, gdy ten serwlet (albo dowolny inny program)
 *  zmieni zakres oferty dnia.
 *  <P>
 *  Taken from Core Servlets and JavaServer Pages Volume II
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://volume2.coreservlets.com/.
 *  (C) 2007 Marty Hall, Larry Brown, and Yaakov Chaikin;
 *  may be freely used or adapted.
 */
public class ChangeDailySpecial extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
       throws ServletException, IOException {
    String dailySpecialNames =
      request.getParameter("newSpecials");
    if ((dailySpecialNames == null) ||
        (dailySpecialNames.equals(""))) {
      dailySpecialNames = "MISSING-VALUE";
    }
    ArrayList<String> specials = new ArrayList<String>();
    String[] dailySpecials = dailySpecialNames.split("\\s++");
    for (String special : dailySpecials) {
      specials.add(special);
    }
    ServletContext context = getServletContext();
    context.setAttribute("daily-special-item-names",
                         specials);
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
      "Transitional//EN\">\n";
    String title = "Nowe oferty dnia";
    out.println
      (docType +
       "<HTML>\n" +
       "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
       "<BODY BGCOLOR=\"#FDF5E6\">\n" +
       "<H2 ALIGN=\"CENTER\">" + title + "</H2>\n" +
       "<UL>");
    String special;
    for(int i=0; i<specials.size(); i++) {
      special = (String)specials.get(i);
      out.println("<LI>" + special);
    }
    out.println("</UL>\n" +
                "</BODY></HTML>");
  }
}
