package Controller;

import Dao.LoginDao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import LoginDb.*;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
import java.sql.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LoginServlet extends HttpServlet {

    public static Map<String, HttpSession> sesssionMap = new ConcurrentHashMap<String, HttpSession>();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            //no code
        } finally {
            out.close();
        }
    }

    public LoginServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(false);

       // String user = request.getParameter("UID");
      //  String pass = request.getParameter("PWD");
       // String pacsId = request.getParameter("PACSID");
       // String moduleName = request.getParameter("moduleName");

        session.setAttribute("user", user);
        session.setAttribute("pass", pass);
        session.setAttribute("pacsId", pacsId);
        session.setAttribute("moduleName", moduleName);

        String Mobile = null; //added on 29/8/24
        String UserName = null;
        String pacsName = null;
        String Login_flag = null;
        String userRole = null;
        String RoleName = null;
        String subPacsFlag = null;
        String headPacsId = null;
        String pwdExpireyFlag = null;
        String holidayList = "";
        String sysIP = "";
        String userAgent = "";
        String kccBalanceTransfer = "";

        Connection connection = null;
        ResultSet resultset = null;
        Statement statement = null;
        String privResult = null;
        String eodStatus = null ; // Added on 01/08/2024 due to EOD enhancement;
        String returnMessage = null; // Added on 29/09/2024 for broadcast message;
        connection = DbHandler.getDBConnection();

        LoginDao lDao = null;
        int result = 0;

        try {
            statement = connection.createStatement();
        } catch (SQLException ex) {
            // Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error occurred during processing.");
        }

        //added by Bishnu to validate mobile login for Non-DDS
        userAgent = request.getHeader("User-Agent");
        System.out.println("user content: " + userAgent);

        //if (!userAgent.contains("Firefox")) {
        //System.out.println("Kindly use Firefox browser.");
        //request.setAttribute("error", "Login is allowed from Firefox browser only.");
        //(request.getRequestDispatcher("/Login.jsp")).forward(request, response);}
        if (userAgent.contains("Tablet") || userAgent.contains("Mobile") || userAgent.contains("x86_64") || userAgent.contains("X11")) {
            System.out.println("Unauthorized login occurred.");
            request.setAttribute("error", "Login from unauthorized device is not allowed.");
            (request.getRequestDispatcher("/Login.jsp")).forward(request, response);
        } else {
            if (request != null) {
                sysIP = request.getHeader("X-FORWARDED-FOR");
                if (sysIP == null || "".equals(sysIP)) {
                    sysIP = request.getRemoteAddr();
                }
            }
            System.out.println(sysIP);

            if (user == null || user.length() == 0 || pass == null || pass.length() == 0) {

                request.setAttribute("error", "Username & Password cannot be empty.");

            } else {
                try {
                    //pass = LoginDb.passwordEncryption.Encr_pass(pass, "SECRETKEY");

                    pass = LoginDb.SimpleCrypt.doEnrcypt(pass);
                  //  String[] ans = new DbConnection().validateUserLogin(request.getParameter("UID"), request.getParameter("PWD"), request.getParameter("PACSID"));

                    String UsrPass = ans[0];        //** addded by Bishnu to verify Static IP address **//
                    String IPAddress = ans[1];
                    String IPflag = ans[2];
                    String pacs = ans[3];

                    if (pacs == "") {
                        request.setAttribute("error", "Invalid credentials provided.");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    } else if (IPflag.equals("Y") && IPAddress == null) {
                        request.setAttribute("error", "Your System IP is not registered.");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    } //                else if (!pacs.equals(pacsId)) {
                    //                  request.setAttribute("error", "Invalid PACS ID/ Bank ID.");
                    //                  request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    //                }
                    else {
                        if (IPflag.equals("N") || (IPAddress.equals(sysIP) && IPflag.equals("Y"))) {

                            if (UsrPass.equals(pass)) {

                                try {

                                    //ResultSet rs = statement.executeQuery("select l.user_role_id,s.role_name, l.login_name as login_name,p.pacs_name as pacs_name,l.first_login_flag,l.IS_PWD_EXPIRED,p.sub_pacs_flag,p.head_pacs_id from login_details l,pacs_master p,sys_roles s where l.password='" + pass + "' and l.login_id='" + user + "' and l.pacs_id='" + pacsId + "' and l.pacs_id=p.pacs_id and s.id=l.user_role_id ");
                                  //  ResultSet rs = statement.executeQuery("select l.user_role_id, l.mobile_no, s.role_name, l.login_name as login_name,p.pacs_name as pacs_name,l.first_login_flag,l.IS_PWD_EXPIRED,p.sub_pacs_flag,p.head_pacs_id from login_details l,pacs_master p,sys_roles s where l.password='" + pass + "' and l.login_id='" + user + "' and l.pacs_id='" + pacsId + "' and l.pacs_id=p.pacs_id and s.id=l.user_role_id ");//added on 29/8/24
                                    while (rs.next()) {

                                        UserName = rs.getString("login_name");
                                        pacsName = rs.getString("pacs_name");
                                        Login_flag = rs.getString("first_login_flag");
                                        userRole = rs.getString("user_role_id");
                                        RoleName = rs.getString("role_name");
                                        subPacsFlag = rs.getString("sub_pacs_flag");
                                        headPacsId = rs.getString("head_pacs_id");
                                        pwdExpireyFlag = rs.getString("IS_PWD_EXPIRED");
                                        Mobile = rs.getString("mobile_no");//added on 29/8/24
                                    }

                                } catch (SQLException ex) {
                                    // Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
                                    System.out.println("Error occurred during processing.");
                                } finally {
                                    try {
                                        if (statement != null) {
                                            statement.close();
                                        }
                                        if (connection != null) {
                                            connection.close();
                                        }

                                    } catch (Exception e) {
                                        System.out.println("Error Occurred during connection close.");
                                    }

                                }

//                                session.setAttribute("UserName", UserName);
//                                session.setAttribute("pacsName", pacsName);
//                                session.setAttribute("userRole", userRole);
//                                session.setAttribute("RoleName", RoleName);
//                                session.setAttribute("subPacsFlag", subPacsFlag);
//                                session.setAttribute("headPacsId", headPacsId);
                                //request.getRequestDispatcher("/welcome.jsp").forward(request, response);
                                if (Login_flag.equalsIgnoreCase("F")) {
                                    //request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                                    response.sendRedirect("./changePassword_fflag.jsp");
                                } else if (pwdExpireyFlag != null && pwdExpireyFlag.equalsIgnoreCase("Y")) {

                                    //request.getRequestDispatcher("/changePassword.jsp").forward(request, response);
                                    response.sendRedirect("./changePassword_fflag.jsp");

                                } else {
                                    lDao = new LoginDao();
                                    if (!lDao.checkIfUserLoggedIn(user, pacsId, 1)) {
                                        //chekForLoginTime Call;
                                        privResult = lDao.checkLoginPrivilages(user, pacsId);
                                        //Added on 01/08/2024 for Eod Status
                                        eodStatus = lDao.checkEodStatus();
                                        System.out.println("EOD Result: "+eodStatus);
                                        returnMessage =lDao.checkBroadcastMessage();
                                        System.out.println("return message is "+returnMessage);
                                                            
                                        if (privResult != null) {
                                           if(eodStatus.equalsIgnoreCase("Success")){
                                            if (privResult.equalsIgnoreCase("TRUE")) {
                                                result = lDao.insertTotLoginDetails(session);
                                                if (result == 1) {
                                                    sesssionMap.put(session.getId(), session);
                                                    holidayList = lDao.findHolidayList(pacsId);
                                                    session.setAttribute("holidayList", holidayList);

                                                    //Added here for broadcast message
                                                    session.setAttribute("returnMessage", returnMessage);

                                                    kccBalanceTransfer = lDao.checkKCCBalanceTransfer(pacsId);
                                                    session.setAttribute("kccBalanceTransfer", kccBalanceTransfer);
                                                    if (userRole.equalsIgnoreCase("201606000004041")) {
                                                        String specialPacs = lDao.checkInterfacePacsOrNot(pacsId);
                                                        if (specialPacs != null) {
                                                            if (specialPacs.equalsIgnoreCase("NEFT")) {
                                                                session.setAttribute("moduleName", "Special");
                                                            } else if (specialPacs.equalsIgnoreCase("KCC")) {
                                                                session.setAttribute("moduleName", "SpecialKcc");
                                                            } else if (specialPacs.equalsIgnoreCase("BOTH") && moduleName.equalsIgnoreCase("KCC")) {
                                                                session.setAttribute("moduleName", "SpecialBothKcc");
                                                            } else if (specialPacs.equalsIgnoreCase("BOTH")) {
                                                                session.setAttribute("moduleName", "SpecialBothDep");
                                                            }
                                                        }
                                                    }
                                                    //added for Two Factor Authentication
                                                    connection = DbHandler.getDBConnection();
                                                    statement = connection.createStatement();
                                                    String otpFlag = null;
                                                    String configId = null;
                                                    String apiKey = null;
                                                    try {
                                                        ResultSet rs = statement.executeQuery("select CONFIG_ID, API_KEY, OTP_FLAG from USER_MFA_DETAILS where PACS_ID='" + pacsId + "'");
                                                        //System.out.println("query executed successfully fetch otp");
                                                        while (rs.next()) {
                                                            otpFlag = rs.getString("OTP_FLAG");
                                                            configId = rs.getString("CONFIG_ID");
                                                            apiKey = rs.getString("API_KEY");
                                                            //System.out.println("debug checkpoint : "otpFlag+" "+configId);
                                                        }

                                                    } catch (SQLException ee) {
                                                        //ee.printStackTrace();
                                                    } finally {
                                                        try {
                                                            statement.close();
                                                            connection.close();
                                                        } catch (SQLException ee) {
                                                            //System.out.println("Error Occurred during connection close.");
                                                        }
                                                    }

                                                    if (apiKey != null && configId != null) {
                                                        if (otpFlag.equals("N")) {
                                                            response.setHeader("Strict-Transport-Security", "max-age=7776000; includeSubdomains");
                                                            session.setAttribute("UserName", UserName);
                                                            session.setAttribute("pacsName", pacsName);
                                                            session.setAttribute("userRole", userRole);
                                                            session.setAttribute("RoleName", RoleName);
                                                            session.setAttribute("subPacsFlag", subPacsFlag);
                                                            session.setAttribute("headPacsId", headPacsId);
                                                            session.setAttribute("Mobile", Mobile);//added on 29/8/24
                                                            response.sendRedirect("./welcome.jsp");
                                                        } else if (otpFlag.equals("Y")) {
                                                            OtpUtility ou = new OtpUtility();
                                                            String verifyId = ou.sendOtp(user, pacsId, request, response);
                                                            //System.out.println("debug checkpoint : fetched verifyId is "+verifyId);
                                                            if (verifyId != null) {
                                                                response.setHeader("Strict-Transport-Security", "max-age=7776000; includeSubdomains");
                                                                request.setAttribute("otp_flag", "valid");// added to show otp form in Login.jsp
                                                                session.setAttribute("verifyId", verifyId);

                                                                ArrayList list = new ArrayList();
                                                                list.add(UserName);
                                                                list.add(pacsName);
                                                                list.add(userRole);
                                                                list.add(RoleName);
                                                                list.add(subPacsFlag);
                                                                list.add(headPacsId);
                                                                session.setAttribute("list", list);

                                                                request.getRequestDispatcher("/Login.jsp").forward(request, response);
                                                            } else {
                                                                request.setAttribute("error", "Error in otp generation.");
                                                                request.getRequestDispatcher("/Login.jsp").forward(request, response);
                                                                session.invalidate();
                                                            }

                                                        }

                                                    } else {
                                                        response.setHeader("Strict-Transport-Security", "max-age=7776000; includeSubdomains");
                                                        session.setAttribute("UserName", UserName);
                                                        session.setAttribute("pacsName", pacsName);
                                                        session.setAttribute("userRole", userRole);
                                                        session.setAttribute("RoleName", RoleName);
                                                        session.setAttribute("subPacsFlag", subPacsFlag);
                                                        session.setAttribute("headPacsId", headPacsId);
                                                        session.setAttribute("Mobile", Mobile);//added on 29/8/24
                                                        response.sendRedirect("./welcome.jsp");
                                                    }

                                                } else {
                                                    request.setAttribute("error", "Error in login.");
                                                    request.getRequestDispatcher("/Login.jsp").forward(request, response);
                                                }
                                            } else if (privResult.equalsIgnoreCase("HOLIDAY")) {
                                                request.setAttribute("error", "User not authorised to login due to holiday.");
                                                request.getRequestDispatcher("/Login.jsp").forward(request, response);

                                            }
                                        }
                                            //Added on 01/08/2024 for EOd status check
                                            
                                            else if (eodStatus.equalsIgnoreCase("Failure")){
                                                request.setAttribute("error", "EOD process not yet completed. Please login after some time.");
                                                request.getRequestDispatcher("/Login.jsp").forward(request, response);
                                            }
                                            
                                            else {
                                                request.setAttribute("error", "User not authorised to login.");
                                                request.getRequestDispatcher("/Login.jsp").forward(request, response);

                                            }
                                        } else {
                                            request.setAttribute("error", "Error in login.");
                                            request.getRequestDispatcher("/Login.jsp").forward(request, response);
                                        }
                                    } else {
                                        System.out.println("Multiple login found for user :" + user);
                                        request.setAttribute("error", "You are already logged in or your previous session is not properly closed.");
                                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                                    }
                                }
                            } else {
                                request.setAttribute("error", "Invalid credentials provided.");
                                request.getRequestDispatcher("/Login.jsp").forward(request, response);

                            }
                        } else {
                            request.setAttribute("error", "Your System IP is not registered.");
                            request.getRequestDispatcher("/Login.jsp").forward(request, response);

                        }
                    }
                } catch (SQLException e) {
                    // e.printStackTrace();
                    System.out.println("Error occurred during processing.");

                } finally {
                    System.out.println("Processing done.");
                }
            } //logic ends
        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
