/**
 *
 */
package common;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author user
 *
 */
public class Chokomaro extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String contentType = "text/html; charset=UTF-8";
		response.setContentType(contentType);

		String envPath = getServletContext().getRealPath("/conf/env.ini");
		Environment env = Environment.getEnvironment();
		env.init(envPath);

		HttpSession session = request.getSession(false);

		String in_application = request.getParameter("application");
		String in_userid = "";

		if ( session != null ) {
			session.getAttribute("userid");
		}

		if ( session == null ) {
			in_application = "login";
		}
		else {
			in_userid = (String)session.getAttribute("userid");
			if ( in_userid == null || in_userid.isEmpty() ) {
				session.invalidate();
				session = null;
				in_application = "login";
			}
			else if ( in_application != null && in_application.equals("logout") ) {
				session.invalidate();
				session = null;
				in_application = "login";
			}
			else if ( in_application == null ) {
				in_application = "home";
			}
			else {
				session.setAttribute("application", in_application);
			}
		}

		//遷移先パス設定
		String path = "";
		path = "./jsp/" + in_application + ".jsp";

		RequestDispatcher rd = request.getRequestDispatcher(path);
		rd.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String contentType = "text/html; charset=UTF-8";
		response.setContentType(contentType);

		String envPath = getServletContext().getRealPath("/conf/env.ini");
		Environment env = Environment.getEnvironment();
		env.init(envPath);

		HttpSession session = request.getSession(false);

		String in_userid = request.getParameter("userid");
		String in_password = request.getParameter("password");

		String query = "";
		if ( in_password.isEmpty() ) {
			query = "person_number = '" + in_userid + "' and password is null";
		}
		else {
			query = "person_number = '" + in_userid + "' and password = '" + in_password + "'";
		}

		Person user = new Person();

		ArrayList<String> params = new ArrayList<String>();
		params.add("person_number");

		ArrayList<ArrayList<String>> results;
		results = user.select(params, query);

		String path = "";
		if ( results.size() > 0 ) {
			path = "./jsp/home.jsp";
			session.setAttribute("userid", in_userid);
		}
		else {
			path = "./jsp/login.jsp";
		}

		RequestDispatcher rd = request.getRequestDispatcher(path);
		rd.forward(request, response);
	}
}
