package controller;

import dao.impl.UserDBImpl;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.UserInfo;

import java.io.IOException;

@WebServlet("/userAction/*")
public class UserController extends BaseController {
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("µÇÂ¼");
        String path = req.getContextPath();
        if (req.getSession().getAttribute("user") != null){
            resp.sendRedirect(path+"/home.jsp");
        }
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserInfo user = new UserDBImpl().getUserByName(username);
        if(user == null) {
            resp.sendRedirect(path+"/login/login.jsp&loginflag=1");
        }else if (user.getPass().equals(password)) {
            req.getSession().setAttribute("user", user);
            resp.sendRedirect(path+"/home.jsp");
        }else{
            resp.sendRedirect(path+"/login/login.jsp&loginflag=2");
        }
    }
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("×¢Ïú");
        String username = req.getParameter("username");
        UserInfo user = (UserInfo)req.getSession().getAttribute("user");
        if(user != null) {
            req.getSession().removeAttribute("user");
        }
        String path = req.getContextPath();
        resp.sendRedirect(path+"/login/login.jsp");
    }
}
