package login;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

public class UserAction extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String path = req.getContextPath();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        int flag;
        try{
            UserDB userdb = new UserDB();
            UserInfo user = userdb.GetUserInfoByName(username);
            if(user == null) {
                flag = 1;
            }else if (user.getPass().equals(password)) {
                flag=0;
                req.getSession().setAttribute("user", userdb.GetUserInfoByName(username));
            }else{
                flag=2;
            }
            System.out.println(user);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            flag=3;
        }
        if(flag==0){
            res.sendRedirect(path+"/user_info.jsp");
        }else{
            res.sendRedirect(path+"/login.jsp?loginflag="+flag+"&username="+username);
        }
    }
}
