/**
 * 
 */
package org.mynonglam.controllers;

import java.io.IOException;

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

import org.mynonglam.dao.AccountDAO;
import org.mynonglam.entitys.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Dao
 * 
 */
@Controller
public class LoginUser {
	private AccountDAO accountdao;

	/**
	 * 
	 */
	public LoginUser() {
		accountdao = new AccountDAO();
	}
	
	@RequestMapping(value = "login")
	public String login() {
		return "login";
	}

	@RequestMapping(value = "loginuser", method = RequestMethod.POST)
	public String loginuser(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
		String result = "login";

		String username = request.getParameter("email");
		String password = request.getParameter("password");

		// information not invalid
		if (username != null && password != null && username != ""
				&& password != "") {
			// check login
			if (accountdao.checkLogin(username.trim(), Account.md5(password.trim()))) {
				if(accountdao.checkIsClock(username)) {
					session.setAttribute("accountinfo", username);
					try {
						response.sendRedirect("index.jsp?acc=" + username);
					} catch (IOException e) {
						result = "index";
						e.printStackTrace();
					}
				} else {
					request.setAttribute("mess", "lockacc");
				}
			} else {
				request.setAttribute("mess", "error");
			}
		}
		return result;
	}
	
	@RequestMapping(value = "loginuser", method = RequestMethod.GET)
	public String loginuserget() {
		return "redirect:login";
	}
	
	//logoutacc
	@RequestMapping(value = "logoutacc", method = RequestMethod.GET)
	public String logoutacc(HttpSession session) {
		session.removeAttribute("accountinfo");
		return "redirect:login";
	}

}
