/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Dao;

import LoginDb.DbHandler;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;
import oracle.jdbc.OracleTypes;

/**
 *
 * @author 1004242
 */
public class LoginDao {

    public int insertTotLoginDetails(HttpSession session) {
        Connection con = null;
        StringBuilder userLoginDetailsInsertquery = null;
        PreparedStatement ps = null;
        int res = 0;
        String sessionId = session.getId();
        String user = (String) session.getAttribute("user");
        String pacsId = (String) session.getAttribute("pacsId");
        try {
            con = DbHandler.getDBConnection();
            userLoginDetailsInsertquery = new StringBuilder("INSERT INTO logged_in_users  (SESSION_ID,USER_ID,LOGIN_TIME,PACS_ID) values (?,?,sysdate,?)");

            ps = con.prepareStatement(userLoginDetailsInsertquery.toString());
            ps.setString(1, sessionId);
            ps.setString(2, user);
            ps.setString(3, pacsId);


            res = ps.executeUpdate();

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured inserting  details in login_details for pacs :" + pacsId + " and user Id :" + user);
           System.out.println("Error occurred during processing.");
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
        return res;

    }

    public boolean checkIfUserLoggedIn(String user, String pacsId, int temp) {
        Connection con = null;
        StringBuilder checkUserLoggedInQuery = null;
        PreparedStatement ps = null;
        ResultSet res = null;

        try {
            con = DbHandler.getDBConnection();

            checkUserLoggedInQuery = new StringBuilder("select * from logged_in_users where ");
            if (temp == 1) {
                checkUserLoggedInQuery.append(" user_id = ? and pacs_Id = ?");
            } else if (temp == 0) {
                checkUserLoggedInQuery.append(" session_id = ? and pacs_Id = ?");
            }

            ps = con.prepareStatement(checkUserLoggedInQuery.toString());
            ps.setString(1, user);
            ps.setString(2, pacsId);

            res = ps.executeQuery();
            if (res.next()) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured fetching  details in logged_in_users for user Id :" + user);
            System.out.println("Error occurred during processing.");
            return false;
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
                System.out.println("Error occurred during connection close.");
            }
        }
    }

    public boolean verifySamPacsForUser(String userModifiable, String userLoggedInPacs) {
        Connection con = null;
        StringBuilder checkUserPacs = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        String userModifiablePacs = null;


        try {
            con = DbHandler.getDBConnection();
            checkUserPacs = new StringBuilder("select pacs_id from login_details where login_id = ? and pacs_id = ?");

            ps = con.prepareStatement(checkUserPacs.toString());
          //  ps.setString(1, userLoggedInPacs);
            ps.setString(1, userModifiable);
            ps.setString(2, userLoggedInPacs);

            res = ps.executeQuery();
            if (res.next()) {
                userModifiablePacs = res.getString("pacs_id");
                if (userLoggedInPacs.equalsIgnoreCase(userModifiablePacs)) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured fetching  details in verifySamPacsForUser for user Id :" + userModifiable);
            System.out.println("Error occurred during processing.");
            return false;
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
    }

    public boolean resetUserPassword(String userModifiable, String userLoggedInPacs) {
        Connection con = null;
        StringBuilder checkUserPacs = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        try {
            con = DbHandler.getDBConnection();
            checkUserPacs = new StringBuilder("update login_details l set l.password='77+977+9Wd6T77+977+977+977+977+977+977+9fV5e77+9UFPvv73vv73vv71S77+977+977+9\n" +
                                                "TUFkC++/vQrvv70=', l.FIRST_LOGIN_FLAG='F' where l.login_id= ? and l.pacs_id = ?");
            ps = con.prepareStatement(checkUserPacs.toString());
            ps.setString(1, userModifiable);
            ps.setString(2, userLoggedInPacs);
            res = ps.executeQuery();
           // con.commit();
            return true;
//            if (res.next()) {
//                userModifiablePacs = res.getString("pacs_id");
//                if (userLoggedInPacs.equalsIgnoreCase(userModifiablePacs)) {
//                    return true;
//                }
//            }
            //return true;
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured fetching  details in resetUserPassword for user Id :" + userModifiable);
            System.out.println("Error occurred during processing.");
           return false;
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
    }

    public List<String> deleteFromLoggedInUser(String userId, String pacsId) {
        Connection con = null;
        StringBuilder deletUserFromLoggedIn = null;
        StringBuilder selectUserSessionFromLoggedIn = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        int result = 0;
        List<String> userSessionList = new ArrayList<String>();
        try {
            con = DbHandler.getDBConnection();
            selectUserSessionFromLoggedIn = new StringBuilder("select SESSION_ID from logged_in_users where user_id = ? and pacs_Id = ? ");

            ps = con.prepareStatement(selectUserSessionFromLoggedIn.toString());
            ps.setString(1, userId);
            ps.setString(2, pacsId);

            res = ps.executeQuery();
            while (res.next()) {
                userSessionList.add(res.getString("SESSION_ID"));
            }
            System.out.println("Session Entry found for the  user Id :" + userId + "in loggedIn_users:" + userSessionList.size());

            ps = null;
            res = null;
            deletUserFromLoggedIn = new StringBuilder("delete from logged_in_users where user_id = ? and pacs_Id = ?");
            ps = con.prepareStatement(deletUserFromLoggedIn.toString());
            ps.setString(1, userId);
            ps.setString(2, pacsId);

            result = ps.executeUpdate();
            if (result != 0) {
                System.out.println("Session Entry deleted for the  user Id :" + userId + "in loggedIn_users:" + res);
            }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured fetching  details in deleteFromLoggedInUser for user Id :" + userId);
            System.out.println("Error occurred during processing.");
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
        return userSessionList;
    }

    public int insertToResetLoginActivity(String ownerUser, String resetableUser, String pacsId) {
        //
        Connection con = null;
        StringBuilder userLoginResetActivityInsertquery = null;
        PreparedStatement ps = null;
        int res = 0;
        String narration = "User Id " + resetableUser + " login status reset";
        java.util.Date myDate = new java.util.Date();
        java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
        try {
            con = DbHandler.getDBConnection();
            userLoginResetActivityInsertquery = new StringBuilder("INSERT INTO user_activity  (PACS_ID,USER_ID,POST_DATE,POST_TIME,ACTIVITY_TYP,NARATION) values (?,?,?,to_date(to_char(SYSTIMESTAMP, 'DD-MON-RRHH24:MI:SS'),'DD-MON-RRHH24:MI:SS'),?,?)");

            ps = con.prepareStatement(userLoginResetActivityInsertquery.toString());
            ps.setString(1, pacsId);
            ps.setString(2, ownerUser);
            ps.setDate(3, sqlDate);
            ps.setString(4, "FORCE LOGOUT");
            ps.setString(5, narration);

            res = ps.executeUpdate();

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured inserting  details in user_activity for pacs :" + pacsId + " and user Id :" + ownerUser);
           System.out.println("Error occurred during processing.");
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
        return res;

    }

    public String findHolidayList(String pacsId) {
        Connection con = null;
        PreparedStatement ps = null;
        Statement qry = null;
        ResultSet rs = null;
        String holidayList = "";
        int i = 0;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
           // rs = qry.executeQuery("select to_char(h.holiday_dt, 'DD-MON-YYYY') h_dt, upper(h.reason)"
                    + "  from holiday_list h"
                    + " where (select system_date from system_date) <= h.holiday_dt and h.holiday_dt - (select system_date from system_date) <= 15"
                    + " order by h.holiday_dt");

           while(rs.next()){
               if(i > 0)
                   holidayList = holidayList + ", ";

               holidayList = holidayList + rs.getString(1) + " (" + rs.getString(2) + ")";
               i = i + 1;
           }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured while checking holiday list");
           System.out.println("Error occurred during processing.");
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }

        return holidayList;
    }

public String checkKCCBalanceTransfer(String pacsId) {
        Connection con = null;
        PreparedStatement ps = null;
        Statement qry = null;
        ResultSet rs = null;
        String kccBalanceTransfer = "";
        
        int i = 0;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
          //  rs = qry.executeQuery("select distinct dccb_name ||                 ' on ' || to_char(trunc(sysdate - 1),'DD-MM-YYYY')   from dccb_br_map r  where r.dccb_code in        (select distinct dccb_code           from kcc_sftp_log li          where to_date(li.proc_dt, 'DDMMYYYY') = trunc(sysdate) - 1            and li.file_id not in                (select L.file_id                   from rupay_kcc_response_sal_files l                  where to_date(l.proc_dt, 'DDMMYYYY') = trunc(sysdate) - 1)            and li.file_type = 'SBZERO')");

           while(rs.next()){
               if(i > 0)
                   kccBalanceTransfer = kccBalanceTransfer + ", ";

                    kccBalanceTransfer = kccBalanceTransfer + rs.getString(1);
                    i = i + 1;
           }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured while checking holiday list");
           System.out.println("Error occurred during processing.");
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }

        return kccBalanceTransfer;
    }

//    public boolean checkIfDiffeUserLoggedInWithSameSession(String sessionId)
//    {
//        Connection con = null;
//        StringBuilder checkUserLoggedInQuery = null;
//        PreparedStatement ps = null;
//        ResultSet res = null;
//
//        try {
//            con = DbHandler.getDBConnection();
//            checkUserLoggedInQuery = new StringBuilder("select * from logged_in_users where session_id = ?");
//
//            ps = con.prepareStatement(checkUserLoggedInQuery.toString());
//            ps.setString(1, sessionId);
//
//            res = ps.executeQuery();
//            if (res.next()) {
//
//                if(res.getString("user_id").equalsIgnoreCase())
//                return true;
//            } else {
//                return false;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("Exception occured fetching  details in logged_in_users for user Id :" + user);
//            return false;
//        } finally {
//            try {
//
//                if (con != null) {
//                    con.close();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
    public String checkLoginPrivilages(String user, String userLoggedInPacs) {
        Connection con = null;
        Connection con2 = null;
        CallableStatement proc = null;
        StringBuilder checkUserPacs = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        String userModifiablePacs = null;
        String result = null;
        int count = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String time = sdf.format(new Date());


        try {
            con = DbHandler.getDBConnection();
            checkUserPacs = new StringBuilder("select count(*) from holiday_list h where h.holiday_dt = (select system_date from system_date)");

            ps = con.prepareStatement(checkUserPacs.toString());
            res = ps.executeQuery();
            
            if (res.next()) {

                if (res.getInt(1) > 0) {
                    return "HOLIDAY";//Restrict login on Holiday
                } else {
                    result = "TRUE";// allow login if not a holiday
                }
            }
            
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured while checking for holiday list");
            System.out.println("Error occurred during processing.");
            return result;
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
                
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }


        try {
            con = DbHandler.getDBConnection();
            checkUserPacs = new StringBuilder("select count(1) as countEntry from pacs_ip_map p where p.pacs_id=? and p.status='Y'");

            ps = con.prepareStatement(checkUserPacs.toString());
            ps.setString(1, userLoggedInPacs);

            res = ps.executeQuery();
            // count= res.getInt("countEntry");
            if (res.next()) {

                if (res.getInt("countEntry") > 0) {
                    con2 = DbHandler.getDBConnection();
                    proc = con.prepareCall("{ call user_maintenance.user_validation(?,?,?,?,?) }");

                    proc.setString(1, userLoggedInPacs);
                    proc.setString(2, user);
                    proc.setString(3, null);
                    proc.setString(4, time);
                    proc.registerOutParameter(5, OracleTypes.VARCHAR);

                    proc.executeUpdate();
                    result = proc.getString(5);//error message from dds procedure
                } else {
                    result = "TRUE";// allow login fi no entry in ip table.
                }
            } else {
                result = "TRUE";// allow login fi no entry in ip table.
            }
            return result;
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured fetching  details in verifySamPacsForUser for user Id :" + userModifiablePacs);
            System.out.println("Error occurred during processing.");
            return result;
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
                if (con2 != null) {
                    con2.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
    }

    public String checkInterfacePacsOrNot(String pacsId) {
        Connection con = null;
        StringBuilder checkPacs = null;
        PreparedStatement ps = null;
        ResultSet res = null;

        try {
            con = DbHandler.getDBConnection();

            checkPacs = new StringBuilder("select * from pacs_neft_interface where pacs_id= ? and status='ACTIVE' ");


            ps = con.prepareStatement(checkPacs.toString());
            ps.setString(1, pacsId);

            res = ps.executeQuery();
            if (res.next()) {
                return res.getString("TYPE");
            } else {
                return null;
            }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured fetching  details in checkInterfacePacsOrNot for Pacs Id :" + pacsId);
            System.out.println("Error occurred during processing.");
            return null;
        } finally {
            try {

                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
    }

    public String checkEodStatus() {

        Connection conn = DbHandler.getDBConnection();
        ResultSet rs = null;
        String eodResult = null;

        try {
            String eodSQL = "select COALESCE(TRNSFR_2_TEMP_STATUS,TRNSFR_2_DEPPRETRIALBAL_STATUS) as TRNSFR_2_TEMP_STATUS,TRNSFR_2_DEPPRETRIALBAL_STATUS from Dep_Account_Data_Transfer_Logs where system_date = (select to_char(trunc(SYSTEM_DATE - 1),'DD-MON-YY') from SYSTEM_DATE) ";
            PreparedStatement ps = conn.prepareStatement(eodSQL);
            rs = ps.executeQuery();

            if (rs.next()) {

                String TRNSFR_2_TEMP_STATUS = rs.getString("TRNSFR_2_TEMP_STATUS");
                System.out.println("the value of TRNSFER is "+TRNSFR_2_TEMP_STATUS);

                String TRNSFR_2_DEPPRETRIALBAL_STATUS = rs.getString("TRNSFR_2_DEPPRETRIALBAL_STATUS");

                if (TRNSFR_2_DEPPRETRIALBAL_STATUS != null) {
                    eodResult = "Success";

                } else {
                    eodResult = "Failure";
                }
            } else{
                eodResult = "Success";
            }
            return eodResult;
        } catch (Exception e) {
            e.printStackTrace();

            System.out.println("Error occurred during processing.");
            return eodResult;
        } finally {
            try {

                if (conn != null) {
                    conn.close();
                }

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

public String checkBroadcastMessage() {
        String broadcastMessage = null;
        String returnMessage = null;
        Connection connection = null;
        //  ResultSet rs = null;
        //  PreparedStatement statement = null;
        try {
            connection = DbHandler.getDBConnection();
            String query = "select message from BROADCAST_MESSAGE where trunc(CREATED_AT)= trunc(SYSDATE)";
            PreparedStatement statement = connection.prepareStatement(query);
           // ResultSet rs = statement.executeQuery();
            if (rs.next()) {
                broadcastMessage = rs.getString("message");
                System.out.println("broad:" + broadcastMessage);
                if (broadcastMessage != null) {
                    //session.setAttribute("messagevisible", true);
                    returnMessage = broadcastMessage;
                
                } else {
                    // session.setAttribute("messagevisible", false);
                    returnMessage = "False";
                }
                rs.close();
                statement.close();
            }
            return returnMessage;
        } catch (Exception e) {
            e.printStackTrace();
            return returnMessage;
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException se) {
            }
        }
    }


}
