/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Dao.ChangeUserPasswordDao;
import LoginDb.SimpleCrypt;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 1004242
 */
public class ChangeUserPasswordServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ChangeUserPasswordDao cPwdDao = new ChangeUserPasswordDao();
        HttpSession session = request.getSession(false);
        String newPass = SimpleCrypt.doEnrcypt(request.getParameter("newpass"));
        String login_id = (String) session.getAttribute("user");
        String pacs_Id = (String) session.getAttribute("pacsId");
        int changePasswordFlag = 0;
        if (login_id == null) {
            //in case of sesssion out.
            // response.sendRedirect("/Login.jsp");
            // (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
        System.out.println("LogOut completed1.");
        request.setAttribute("error", "You have logged out successfully.");
        (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
            return;
        }
        String prevPwdOld = null;
        String prevPwd = null;
        String currentPwd = null;
        List<String> passwordList = new ArrayList<String>();
        try {
            passwordList = cPwdDao.CheckPreviousPwd(login_id);
            currentPwd = passwordList.get(0);
            prevPwd = passwordList.get(1);
            prevPwdOld = passwordList.get(2);

            //first time login case. all previous pwd entries are null.
            if (prevPwd == null && prevPwdOld == null) {
                if (!currentPwd.equalsIgnoreCase(newPass)) {
                    changePasswordFlag = cPwdDao.updateNewAndOldPwd(login_id, newPass, currentPwd, prevPwd, pacs_Id);
                    if (changePasswordFlag == 1) {
                        //request.setAttribute("error", "Your Password has been changed successfully.Try login with the new credential.");
                       // response.sendRedirect("/Login.jsp");
                        session.removeAttribute("user");
                        session.invalidate();
                        System.out.println("LogOut completed2.");
                        request.setAttribute("error", "You have logged out successfully.");
                        (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
                        

                    } else {
                        request.setAttribute("error", "Password change unsuccesful.Please try again.");
                        request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                    }
                } else {
                    changePasswordFlag = -999;
                    request.setAttribute("error", "New password can not be same as the last three passwords.Retry with different password.");
                    request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                }
            } //Second time login case. previous old pwd entry is null.
            else if (prevPwd != null && prevPwdOld == null) {
                if (!currentPwd.equalsIgnoreCase(newPass) && !prevPwd.equalsIgnoreCase(newPass)) {
                    changePasswordFlag = cPwdDao.updateNewAndOldPwd(login_id, newPass, currentPwd, prevPwd, pacs_Id);
                    if (changePasswordFlag != 0) {
                       // response.sendRedirect("/Login.jsp");
                       //(request.getRequestDispatcher("/Login.jsp")).forward(request, response);
                        session.removeAttribute("user");
                        session.invalidate();
                        System.out.println("LogOut completed3.");
                        request.setAttribute("error", "You have logged out successfully.");
                        (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
                        
                    } else {
                        request.setAttribute("error", "Password change unsuccesful.Please try again.");
                        request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                    }
                } else {
                    changePasswordFlag = -999;
                    request.setAttribute("error", "New password can not be same as the last three passwords.Retry with different password.");
                    request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                }
            }//invalid case.should be cleaned up ffrom db 
            else if (prevPwd == null && prevPwdOld != null) {
                changePasswordFlag = -998;
                request.setAttribute("error", "Password reset structure problem.Please contact IPKS team.");
                request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                session.removeAttribute("user");
                session.invalidate();
            }//Optimal case.General case reset.
            else {
                //optimal case. Password validated for reset.
                if (!currentPwd.equalsIgnoreCase(newPass) && !prevPwd.equalsIgnoreCase(newPass) && !prevPwdOld.equalsIgnoreCase(newPass)) {
                    changePasswordFlag = cPwdDao.updateNewAndOldPwd(login_id, newPass, currentPwd, prevPwd, pacs_Id);
                    if (changePasswordFlag != 0) {
                       // response.sendRedirect("/Login.jsp");
                       // (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
                        session.removeAttribute("user");
                        session.invalidate();
                        System.out.println("LogOut completed4.");
                        request.setAttribute("error", "You have logged out successfully.");
                        (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
                        
                    } else {
                        request.setAttribute("error", "Password change unsuccesful.Please try again.");
                        request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                    }
                }// new password is same with any of the last three passwords
                else {
                    changePasswordFlag = -999;
                    request.setAttribute("error", "New password can not be same as the last three passwords.Retry with different password.");
                    request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                }
            }
        } catch (Exception e) {
           // e.printStackTrace();
            System.out.println("Error occurred during processing.");
            request.setAttribute("error", "Password change unsuccesful.Please try again.");
            request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
//            session.removeAttribute("user");
//            session.invalidate();
        } finally {
            System.out.println("Password changed successfully.");
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
