package com.wxpn.tutorial.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: SimpleVoteServlet
 */
public class SimpleVoteServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public SimpleVoteServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vote = request.getParameter("vote");
		if (vote == null) {
			response.sendRedirect("simple_showvote.jsp");
		} else if (vote.equals("A")) {
			Counter counter = new Counter();
			int a = Integer.parseInt(counter.readFile(request
					.getRealPath("a.txt")));
			counter.writeFile(request.getRealPath("a.txt"), a + 1);
		} else if (vote.equals("B")) {
			Counter counter = new Counter();
			int a = Integer.parseInt(counter.readFile(request
					.getRealPath("b.txt")));
			counter.writeFile(request.getRealPath("b.txt"), a + 1);
		} else if (vote.equals("C")) {
			Counter counter = new Counter();
			int a = Integer.parseInt(counter.readFile(request
					.getRealPath("c.txt")));
			counter.writeFile(request.getRealPath("c.txt"), a + 1);
		}
		request.getSession(true).setAttribute("voted","true");
		Cookie cookie=new Cookie("votedCookie", "true"); 
		cookie.setMaxAge(365*24*60*60); 
		response.addCookie(cookie); 	
		response.sendRedirect("simple_showvote.jsp");
	}
}