package com.wxpn.tutorial.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

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

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

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("<title>新增投票</title>");
		out.println("</head>");
		out.println("<body>");

		String title = request.getParameter("title");
		String style = request.getParameter("style");
		String startTime = request.getParameter("startyear") + "-"
				+ request.getParameter("startmonth")+ "-"
				+ request.getParameter("startday");
		String endTime = request.getParameter("endyear") + "-"
				+ request.getParameter("endmonth")+ "-"
				+ request.getParameter("endday");
		String active = request.getParameter("active");
		Question question = new Question();
		question.setTitle(title);
		question.setStyle(style);
		question.setStrStartime(startTime);
		question.setStrEndtime(endTime);
		question.setActive(Integer.parseInt(active));

		int n = Integer.parseInt(request.getParameter("n"));
		Collection items = new ArrayList();
		Item item = null;
		for (int i = 1; i <= n; i++) {
			item=new Item();
//			System.out.println(request.getParameter("option" + i));
			item.setOptions(request.getParameter("option" + i));
			items.add(item);
			item=null;
		}

		VoteMgr mgr = new VoteMgr();
		question.setItems(items);
		int i = mgr.addVote(question);
		if (i == 1) {
			// 撰写新增投票成功
			out.println("<h1>新增投票成功!</h1>");
		} else {
			// 否则，表明新增投票失败：
			out.println("<h1>新增投票失败!</h1>");
		}
		out.println("<a href=admin/addVote.jsp>继续增加投票</a>|");
		out.println("<a href=BrowseVoteServlet>浏览投票项目</a>|");
		out.println("</body>");
		out.println("</html>");
	}
}