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

import DataEntryBean.TransactioDetailsBean;
import LoginDb.DbHandler;
import java.io.FileWriter;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import oracle.jdbc.OracleTypes;
import org.codehaus.jackson.map.ObjectMapper;

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

      public String bulkMarkAccounts(String accNo, String pacsId) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        List<TransactioDetailsBean> tdBeanList = new ArrayList<TransactioDetailsBean>();
        TransactioDetailsBean tdBean = null;
        ObjectMapper objmap = new ObjectMapper();
        String jsonString = null;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            rs = qry.executeQuery(" select (select p.prod_name from dep_product p where p.id=d.dep_prod_id) as prod,d.key_1,"
                                  +" d.customer_no,(select r.first_name||' '||r.middle_name||' '||r.last_name from kyc_hdr r where r.cif_no=d.customer_no) as cust_name,"
                                  +" nvl((select r.guardian_name from kyc_hdr r where r.cif_no=d.customer_no),'NA') as guardian_name, "
                                  +" (select (case k.id_type when '06' then 'VOTER CARD' when '47' then 'AADHAR CARD' when '08' then 'RATION CARD' when '09' then 'EMPLOYER ID CARD' when '04' then 'PASSPORT' "
                                  +" when '10' then 'DRIVING LICENCE' when '41' then 'INTRODUCED BY MEMBER' when '07' then 'PAN CARD' end) from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' "
                                  +" and k.status = 'R') id_type, (select k.id_number from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' and k.status = 'R') id_number "
                                  +" from dep_account d where d.key_1 not in (select k.key_1 from bulk_acct_mark k where k.pacs_id='"+pacsId+"') and d.dep_prod_id in (select p.id from dep_product p where p.prod_code in ('1101','1102' )"
                                  +" and substr(p.int_cat,0,1)='1') and trim(d.link_accno) is null and  d.pacs_id='"+pacsId+"' and d.key_1 like '%"+accNo+"%' and d.curr_status='O'");

         while (rs.next()) {

                tdBean = new TransactioDetailsBean();
                tdBean.setAuthorisedQ(rs.getString("prod")==null?"NA":rs.getString("prod"));
                tdBean.setRejectedQ(rs.getString("key_1")==null?"NA":rs.getString("key_1"));
                tdBean.setPendingQ(rs.getString("cust_name")==null?"NA":rs.getString("cust_name"));
                tdBean.setCashIn(rs.getString("guardian_name")==null?"NA":rs.getString("guardian_name"));
                tdBean.setCashOut(rs.getString("id_type")==null?"NA":rs.getString("id_type"));
                tdBean.setGuardianName(rs.getString("id_number")==null?"NA":rs.getString("id_number"));
                tdBeanList.add(tdBean);
            }
           jsonString = objmap.writeValueAsString(tdBeanList);
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

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

        return jsonString;
    }

       public String markBulkAccount(String accno , String pacsId , String tellerId) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        String txnType;
        int count = 0;

        try {
            con = DbHandler.getDBConnection();


            proc = con.prepareCall("{ call operations1.BULK_ACCT_MARKING(?,?,?,?) }");

            proc.setString(1, pacsId);
            proc.setString(2, accno);
            proc.setString(3, tellerId);
            proc.registerOutParameter(4, OracleTypes.VARCHAR);

            proc.executeUpdate();

           // res = proc.getString(4);//error message from dds procedure

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in markBulkAccount for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");
            res = "Exception occured  in markBulkAccount for pacs Id :" + pacsId;
        } finally {
            try {
                if (con != null) {
                   // con.commit();
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }

        return "{ \"result\": \" "+res+"\" }" ;
    }

        public String unmarkAccountFromAuth(String accNo, String pacsId, String tellerId) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        int rs = 0;
        List<TransactioDetailsBean> tdBeanList = new ArrayList<TransactioDetailsBean>();
        TransactioDetailsBean tdBean = null;
        ObjectMapper objmap = new ObjectMapper();
        String jsonString = null;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            String query = "insert into bulk_acct_mark_hist (pacs_id, key_1, mark_teller_id, tran_dt, tran_tym, status, remarks, send_teller_id, send_dt, send_tym) select pacs_id, key_1, mark_teller_id, tran_dt, tran_tym, status, 'UNMARKED', " +
                    " " +tellerId+ ", (select system_date from system_date), to_char(SYSTIMESTAMP, 'DD-MON-RRHH12:MI:SS') from bulk_acct_mark where KEY_1= '"+accNo+"' and PACS_ID = '"+pacsId+"'";
            System.out.println(query);
            rs = qry.executeUpdate(query);
            rs = qry.executeUpdate("update bulk_acct_mark set status = 'RBB' where KEY_1= '"+accNo+"' and PACS_ID = '"+pacsId+"'");
            int rs1 = qry.executeUpdate("delete from BULK_ACC_TRICKLEFEED_FILE_auto where add_1= '"+accNo+"' and PACS_ID = '"+pacsId+"'");

          if(rs != 0 && rs1 !=0)
          {
                 res="Account has been unmarked successfully";
          }else
          {
                res="Account unmarking unsuccessfull";
               // con.rollback();
          }
        
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccountsAuth for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");
            res = "Exception occured  in bulkMarkAccountsAuth for pacs Id :" + pacsId;
        } finally {
            try {
                if (con != null) {
                   // con.commit();
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }

        return "{ \"result\": \" "+res+"\" }" ;

        
    }

        public String  bulkMarkAccountsAuth( String pacsId ) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        List<TransactioDetailsBean> tdBeanList = new ArrayList<TransactioDetailsBean>();
        TransactioDetailsBean tdBean = null;
        ObjectMapper objmap = new ObjectMapper();
        String jsonString = null;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            rs = qry.executeQuery(" select (select p.prod_name from dep_product p where p.id=d.dep_prod_id) as prod,d.key_1,"
                                  +" d.customer_no,(select r.first_name||' '||r.middle_name||' '||r.last_name from kyc_hdr r where r.cif_no=d.customer_no) as cust_name,"
                                  +" nvl((select r.guardian_name from kyc_hdr r where r.cif_no=d.customer_no),'NA') as guardian_name, "
                                  +" (select (case k.id_type when '06' then 'VOTER CARD' when '47' then 'AADHAR CARD' when '08' then 'RATION CARD' when '09' then 'EMPLOYER ID CARD' when '04' then 'PASSPORT' "
                                  +" when '10' then 'DRIVING LICENCE' when '41' then 'INTRODUCED BY MEMBER' when '07' then 'PAN CARD' when '38' then 'BOARD RESOLUTION' end) from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' "
                                  +" and k.status = 'R' and k.mark_type = 'N') id_type, (select k.id_number from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' and k.status = 'R' and k.mark_type = 'N') id_number ,"

                                  +" (select (case k.id_type_two when '06' then 'VOTER CARD' when '47' then 'AADHAR CARD' when '08' then 'RATION CARD' when '09' then 'EMPLOYER ID CARD' when '04' then 'PASSPORT' "
                                  +" when '10' then 'DRIVING LICENCE' when '41' then 'INTRODUCED BY MEMBER' when '07' then 'PAN CARD' when '38' then 'BOARD RESOLUTION' end) from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' "
                                  +" and k.status = 'R' and k.mark_type = 'N') id_type_two, (select k.id_number_two from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' and k.status = 'R' and k.mark_type = 'N') id_number_two "

                                  +" from dep_account d where d.dep_prod_id in (select p.id from dep_product p where p.prod_code in ('1101','1102' )"
                                  +" and substr(p.int_cat,0,1)='1') and trim(d.link_accno) is null and  d.pacs_id='"+pacsId+"' and d.key_1 in ( select key_1 from bulk_acct_mark where pacs_id= '"+pacsId+"' and status = 'R' and mark_type = 'N' ) ");

         while (rs.next()) {

                tdBean = new TransactioDetailsBean();
                tdBean.setAuthorisedQ(rs.getString("prod")==null?"NA":rs.getString("prod"));
                tdBean.setRejectedQ(rs.getString("key_1")==null?"NA":rs.getString("key_1"));
                tdBean.setPendingQ(rs.getString("cust_name")==null?"NA":rs.getString("cust_name"));
                tdBean.setCashIn(rs.getString("guardian_name")==null?"NA":rs.getString("guardian_name"));
                tdBean.setCashOut(rs.getString("id_type")==null?"NA":rs.getString("id_type"));
                tdBean.setGuardianName(rs.getString("id_number")==null?"NA":rs.getString("id_number"));
                tdBean.setIdTypeTwo(rs.getString("id_type_two")==null?"NA":rs.getString("id_type_two"));
                tdBean.setIdNumberTwo(rs.getString("id_number_two")==null?"NA":rs.getString("id_number_two"));
                tdBeanList.add(tdBean);
            }
           jsonString = objmap.writeValueAsString(tdBeanList);
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

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

        return jsonString;
    }

     public String  bulkMarkAccountsAuth_Exs( String pacsId ) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        List<TransactioDetailsBean> tdBeanList = new ArrayList<TransactioDetailsBean>();
        TransactioDetailsBean tdBean = null;
        ObjectMapper objmap = new ObjectMapper();
        String jsonString = null;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            rs = qry.executeQuery(" select (select p.prod_name from dep_product p where p.id=d.dep_prod_id) as prod,d.key_1,"
                                  +" d.customer_no,(select r.first_name||' '||r.middle_name||' '||r.last_name from kyc_hdr r where r.cif_no=d.customer_no) as cust_name,"
                                  +" nvl((select r.guardian_name from kyc_hdr r where r.cif_no=d.customer_no),'NA') as guardian_name, "
                                  +" (select (case k.id_type when '06' then 'VOTER CARD' when '47' then 'AADHAR CARD' when '08' then 'RATION CARD' when '09' then 'EMPLOYER ID CARD' when '04' then 'PASSPORT' "
                                  +" when '10' then 'DRIVING LICENCE' when '41' then 'INTRODUCED BY MEMBER' when '07' then 'PAN CARD' when '38' then 'BOARD RESOLUTION' end) from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' "
                                  +" and k.status = 'R' and k.mark_type = 'E') id_type, (select k.id_number from bulk_acc_tricklefeed_file_auto k where k.add_1 = d.key_1 and k.pacs_id = '"+pacsId+"' and k.status = 'R' and k.mark_type = 'E') id_number, "
                                  +" (select r.bank_cif from kyc_hdr r where r.cif_no=d.customer_no) as bank_cif "
                                  +" from dep_account d where d.dep_prod_id in (select p.id from dep_product p where p.prod_code in ('1101','1102' )"
                                  +" and substr(p.int_cat,0,1)='1') and trim(d.link_accno) is null and  d.pacs_id='"+pacsId+"' and d.key_1 in ( select key_1 from bulk_acct_mark where pacs_id= '"+pacsId+"' and status = 'R' and mark_type = 'E' ) ");

         while (rs.next()) {

                tdBean = new TransactioDetailsBean();
                tdBean.setAuthorisedQ(rs.getString("prod")==null?"NA":rs.getString("prod"));
                tdBean.setRejectedQ(rs.getString("key_1")==null?"NA":rs.getString("key_1"));
                tdBean.setPendingQ(rs.getString("cust_name")==null?"NA":rs.getString("cust_name"));
                tdBean.setCashIn(rs.getString("guardian_name")==null?"NA":rs.getString("guardian_name"));
                tdBean.setCashOut(rs.getString("id_type")==null?"NA":rs.getString("id_type"));
                tdBean.setGuardianName(rs.getString("id_number")==null?"NA":rs.getString("id_number"));
                tdBean.setBankCif(rs.getString("bank_cif")==null?"NA":rs.getString("bank_cif"));
                tdBeanList.add(tdBean);
            }
           jsonString = objmap.writeValueAsString(tdBeanList);
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

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

        return jsonString;
    }

     public String authoriseBulk(String pacsId , String tellerId) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        String txnType;
        int count = 0;

        try {
            con = DbHandler.getDBConnection();


            proc = con.prepareCall("{ call generate_bulk_acct_auto(?,?,?) }");


            proc.setString(1, pacsId);
            proc.setString(2, tellerId);

            proc.registerOutParameter(3, OracleTypes.VARCHAR);

            proc.executeUpdate();

            res = proc.getString(3);//error message from dds procedure

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in authoriseBulk for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");
            res = "Something went wrong. Please try agian.";
        } finally {
            try {
                if (con != null) {
                   // con.commit();
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }

        return res ;
    }

      public String  gerateBulkFlatFile( String pacsId , String tellerId ) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
       // File bulkFile = null;
         FileWriter fWrite=null;
        boolean bool = false;

        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
        String date = sdf.format(new Date());
        String bank_code="";
        String brch_code="";
        System.out.println(date);
        
        String  OUTPUT_FOLDER_PATH="";
        String OUTPUT_FILENAME="";         

        try{
           
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream input = classLoader.getResourceAsStream("Dao/BulkMarkSTB.properties");
            Properties properties = new Properties();
            properties.load(input);
             
             OUTPUT_FOLDER_PATH = properties.getProperty("OUTPUT_FOLDER_PATH");
             OUTPUT_FILENAME = properties.getProperty("OUTPUT_FILENAME");
             
        }catch(Exception e){
          // e.printStackTrace();
          System.out.println("Error occurred during processing.");
        }
       // BufferedWriter writer = null;

          try {
              con = DbHandler.getDBConnection();
              qry = con.createStatement();

              //rs = qry.executeQuery("select r.bank_code,p.cbs_br_code from rupay_kcc_api_map r ,pacs_master p where r.dccb_code=p.dccb_code and p.pacs_id='"+pacsId+"'");

              while(rs.next()){
                bank_code = rs.getString("bank_code");
                brch_code = rs.getString("cbs_br_code");
              }
              System.out.println("Bank Code: "+bank_code);

              SimpleDateFormat fileDateFormat = new SimpleDateFormat("ddMMyyyy_HHmmSS_ddMMyyyy");
             String fileDate = fileDateFormat.format(new Date());

             System.out.println(fileDate);
             String fileDate1 = fileDate.substring(0, 15);
             String fileDate2 = fileDate.substring(16, 25);
             String fileDate3 = fileDate1+fileDate2;


             Random r = new Random();
             String seq =""+ (r.nextInt((999 - 100) + 1) + 100);

             System.out.println(OUTPUT_FILENAME);

             OUTPUT_FILENAME = OUTPUT_FILENAME.replace("{BANK_CODE}", brch_code);
             OUTPUT_FILENAME = OUTPUT_FILENAME.replace("{TIMESTAMP}", fileDate3);
             OUTPUT_FILENAME = OUTPUT_FILENAME.replace("{SEQ}", seq);

             OUTPUT_FILENAME = bank_code +"-"+ OUTPUT_FILENAME;
             
             System.out.println(OUTPUT_FILENAME);

              rs = null;
              String sql= "select "
                      + " rpad(nvl(trim(h.record_type),' '),2,' ')||' '||                    "
                      + " rpad(nvl(trim(h.branch_number),' '),5,' ')||' '||                  "
                      + " rpad(nvl(trim(h.account_type),' '),4,' ')||' '||                   "
                      + " rpad(nvl(trim(h.interest_category),' '),4,' ')||' '||	             "
                      + " rpad(nvl(trim(h.segment_code),' '),4,' ')||	' '||                "
                      + " rpad(nvl(trim(h.term_length),' '),4,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.term_basis),' '),1,' ')||' '||                     "
                      + " rpad(nvl(trim(h.term_amount),' '),10,' ')||' '||	                 "
                      //+ " rpad(nvl(trim(h.account_open_date),' '),8,' ')||' '||	             "
                      + " rpad('"+date+"',8,' ')||' '||	             "
                      + " rpad(nvl(trim(h.term_frequency),' '),4,' ')||' '||	             "
                      + " rpad(nvl(trim(h.Term_Days),' '),4,' ')||' '||	                     "
                      + " rpad(nvl(trim(h.term_months),' '),4,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.term_years),' '),4,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.installment_due_date),' '),2,' ')||' '||	         "
                      + " rpad(nvl(trim(h.installment_frequency),' '),1,' ')||' '||	         "
                      + " rpad(nvl(trim(h.language_code),' '),2,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.teller_number),' '),7,' ')||' '||	                 "
                      //+"  rpad(lpad('"+tellerId+"',7,'0'),7,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.stop_required),' '),1,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.data_a),' '),1,' ')||' '||	                     "
                      + " rpad(nvl(trim(h.interest_payment_method_trap),' '),1,' ')||' '||	 "
                      + " rpad(nvl(trim(h.backdate_account_opening_flag),' '),1,' ')||' '||	 "
                      + " rpad(nvl(trim(h.existing_cif),' '),16,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.transfer_account_number),' '),16,' ')||' '||       "
                      + " lpad(nvl(trim(h.description_1),' '),50,' ')||' '||	             "
                      + " rpad(nvl(trim(h.sal_or_other),' '),1,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.employer_name),' '),60,' ')||' '||	             "
                      + " rpad(nvl(trim(h.beneficiary_name),' '),118,' ')	                 "
                      + " from hh_format_auto h where h.pacs_id= "+pacsId+"                     ";
              
              rs = qry.executeQuery(sql);
              System.out.println(sql);

         while (rs.next()) {

           // bulkFile = new File("BulkFlatFile" + System.currentTimeMillis() + ".txt");
           // writer = new BufferedWriter(new FileWriter(bulkFile));

            String header = rs.getString(1);
           // writer.write(header);

           fWrite = new FileWriter(OUTPUT_FOLDER_PATH+OUTPUT_FILENAME);
           fWrite.write(header);
           
            }

              qry = null;
              rs = null;
             //if (bulkFile != null) {
                  qry = con.createStatement();
                  rs = qry.executeQuery("select																	"
                          + "rpad(nvl(trim(t.record_type),' '),2,' ')||                            "
                          + "rpad(nvl(trim(t.student_number),' '),15,' ')||                        "
                          + "rpad(nvl(trim(t.first_name),' '),40,' ')||                            "
                          + "rpad(nvl(trim(t.middle_name),' '),40,' ')||                           "
                          + "rpad(nvl(trim(t.last_name),' '),40,' ')||                             "
                          + "rpad(nvl(trim(t.add_1),' '),40,' ')||                                 "
                          + "rpad(nvl(trim(t.add_2),' '),40,' ')||                                 "
                          + "rpad(nvl(trim(t.add_3),' '),24,' ')||                                 "
                          + "rpad(nvl(trim(t.city_code),' '),3,' ')||                              "
                          + "rpad(nvl(trim(t.state_code),' '),3,' ')||                             "
                          + "rpad(nvl(trim(t.po_number),' '),8,' ')||                              "
                          + "rpad(nvl(trim(t.phn_number),' '),12,' ')||                            "
                          + "rpad(nvl(trim(t.id_type),' '),2,' ')||                                "
                          + "rpad(nvl(trim(t.id_number),' '),14,' ')||                             "
                          + "rpad(nvl(trim(t.birth_date),' '),8,' ')||                             "
                          + "rpad(nvl(trim(t.gender),' '),1,' ')||                                 "
                          + "rpad(nvl(trim(t.mother_name),' '),25,' ')||                           "
                          + "rpad(nvl(trim(t.residential_status),' '),1,' ')||                     "
                          + "rpad(nvl(trim(t.nationality_code),' '),3,' ')||                       "
                          + "rpad(nvl(trim(t.customer_type),' '),8,' ')||                          "
                          + "rpad(nvl(trim(t.title),' '),2,' ')||                                    "

                          + "rpad(nvl(trim(t.id_type_two),' '),2,' ')||                                "
                          + "rpad(nvl(trim(t.id_number_two),' '),14,' ')                            "

                          + "from BULK_ACC_TRICKLEFEED_FILE_auto t where t.pacs_id="+pacsId+" and     "
                          + "t.status='R' and t.mark_type='N' ");
//                          + "(select system_date from system_date)                                ");

         while (rs.next()) {

           // writer.write("\r\n");
             fWrite.write("\r\n");
             //writer.newLine();
            String line1 = rs.getString(1);
            //line1 = line1.replaceAll("\\r|\\n|\\r|\\n", "");
            //String line = rs.getString(1).substring(0, rs.getString(1).length()-2);
            //line1 = line1.trim();
           //writer.write(line1);
           fWrite.write(line1);

            }
            //}
//                  if(writer != null)
//                  {
//                       writer.flush();
//                       writer.close();
//                       fWrite.close();
//                  }
              //updating sttaus of the generated bulks to S
             fWrite.close();
              updateBulkAuthStatusToS(pacsId);
              

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");
            return "Failed to Process request. Please try again";
           // bulkFile = null;

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

        return "File Sent to Destination Server";
    }

    public String  gerateBulkFlatFile_Exs( String pacsId , String tellerId ) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
       // File bulkFile = null;
         FileWriter fWrite=null;
        boolean bool = false;

        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
        String date = sdf.format(new Date());
        String bank_code="";
        String brch_code="";
        System.out.println(date);

        String  OUTPUT_FOLDER_PATH="";
        String OUTPUT_FILENAME="";

        try{

            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream input = classLoader.getResourceAsStream("Dao/BulkMarkSTB.properties");
            Properties properties = new Properties();
            properties.load(input);

             OUTPUT_FOLDER_PATH = properties.getProperty("OUTPUT_FOLDER_PATH");
             OUTPUT_FILENAME = properties.getProperty("OUTPUT_FILENAME");

        }catch(Exception e){
          // e.printStackTrace();
          System.out.println("Error occurred during processing.");
        }
       // BufferedWriter writer = null;

          try {
              con = DbHandler.getDBConnection();
              qry = con.createStatement();

             // rs = qry.executeQuery("select r.bank_code,p.cbs_br_code from rupay_kcc_api_map r ,pacs_master p where r.dccb_code=p.dccb_code and p.pacs_id='"+pacsId+"'");

              while(rs.next()){
                bank_code = rs.getString("bank_code");
                brch_code = rs.getString("cbs_br_code");
              }
              System.out.println("Bank Code: "+bank_code);

              SimpleDateFormat fileDateFormat = new SimpleDateFormat("ddMMyyyy_HHmmSS_ddMMyyyy");
             String fileDate = fileDateFormat.format(new Date());

             System.out.println(fileDate);
             String fileDate1 = fileDate.substring(0, 15);
             String fileDate2 = fileDate.substring(16, 25);
             String fileDate3 = fileDate1+fileDate2;


             Random r = new Random();
             String seq =""+ (r.nextInt((999 - 100) + 1) + 100);

             System.out.println(OUTPUT_FILENAME);

             OUTPUT_FILENAME = OUTPUT_FILENAME.replace("{BANK_CODE}", brch_code);
             OUTPUT_FILENAME = OUTPUT_FILENAME.replace("{TIMESTAMP}", fileDate3);
             OUTPUT_FILENAME = OUTPUT_FILENAME.replace("{SEQ}", seq);

             OUTPUT_FILENAME = bank_code +"-"+ OUTPUT_FILENAME;

             System.out.println(OUTPUT_FILENAME);

              rs = qry.executeQuery("select "
                      + " rpad(nvl(trim(h.record_type),' '),2,' ')||' '||                    "
                      + " rpad(nvl(trim(h.branch_number),' '),5,' ')||' '||                  "
                      + " rpad(nvl(trim(h.account_type),' '),4,' ')||' '||                   "
                      + " rpad(nvl(trim(h.interest_category),' '),4,' ')||' '||	             "
                      + " rpad(nvl(trim(h.segment_code),' '),4,' ')||	' '||                "
                      + " rpad(nvl(trim(h.term_length),' '),4,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.term_basis),' '),1,' ')||' '||                     "
                      + " rpad(nvl(trim(h.term_amount),' '),10,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.account_open_date),' '),8,' ')||' '||	             "
                      + " rpad(nvl(trim(h.term_frequency),' '),4,' ')||' '||	             "
                      + " rpad(nvl(trim(h.Term_Days),' '),4,' ')||' '||	                     "
                      + " rpad(nvl(trim(h.term_months),' '),4,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.term_years),' '),4,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.installment_due_date),' '),2,' ')||' '||	         "
                      + " rpad(nvl(trim(h.installment_frequency),' '),1,' ')||' '||	         "
                      + " rpad(nvl(trim(h.language_code),' '),2,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.teller_number),' '),7,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.stop_required),' '),1,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.data_a),' '),1,' ')||' '||	                     "
                      + " rpad(nvl(trim(h.interest_payment_method_trap),' '),1,' ')||' '||	 "
                      + " rpad(nvl(trim(h.backdate_account_opening_flag),' '),1,' ')||' '||	 "
                      + " lpad(nvl(substr(t.bank_cif, 1, length(t.bank_cif)-1), ' '),16,'0') || ' ' || "
                      //+ " rpad(nvl(trim(h.existing_cif),' '),16,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.transfer_account_number),' '),16,' ')||' '||       "
                      + " rpad(nvl(trim('BULK ACCOUNT'), ' '), 50, ' ') || ' ' || "
                      //+ " lpad(nvl(trim(h.description_1),' '),50,' ')||' '||	             "
                      + " rpad(nvl(trim(h.sal_or_other),' '),1,' ')||' '||	                 "
                      + " rpad(nvl(trim(h.employer_name),' '),60,' ')||' '||	             "
                      + " rpad(nvl(trim(h.beneficiary_name),' '),118,' ')	                 "
                      + " from hh_format_auto h, BULK_ACC_TRICKLEFEED_FILE_auto t where h.pacs_id = t.pacs_id and "
                      + " t.pacs_id="+pacsId+" and t.status='R' and t.mark_type='E' ");

                  fWrite = new FileWriter(OUTPUT_FOLDER_PATH+OUTPUT_FILENAME);
         while (rs.next()) {

            String line1 = rs.getString(1);
            fWrite.write(line1);
            fWrite.write("\r\n");
            fWrite.write("DD000000000000000                                                                                                                                                                                                                                5320000000000000000000000000              00000000                                        ");
            fWrite.write("\r\n");
         }

                  if(fWrite != null)
                  {
                       fWrite.flush();
                       fWrite.close();
                  }
              updateBulkAuthStatusToS_Exs(pacsId);

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");
            return "Failed to Process request. Please try again";
           // bulkFile = null;

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

        return "File Sent to Destination Server";
    }

     public void updateBulkAuthStatusToS(String pacsId) {
        Connection con = null;
        Statement qry = null;
        ResultSet rs = null;
        int count = 0;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            count = qry.executeUpdate(" update bulk_acct_mark k set k.status='S',k.send_dt=(select system_date from system_date),k.send_tym=to_date(to_char(SYSTIMESTAMP, 'DD-MON-RRHH24:MI:SS'),'DD-MON-RRHH24:MI:SS') where k.pacs_id= "+pacsId +" and k.status='R'"
                                     +" and k.key_1 in ( select trim(o.add_1) from BULK_ACC_TRICKLEFEED_FILE_auto o where o.status='R' and o.mark_type='N')");
            if (count > 0) {
                count=0;
                count = qry.executeUpdate(" update BULK_ACC_TRICKLEFEED_FILE_auto o set o.status='S' where o.pacs_id="+pacsId+" and o.status='R' and o.mark_type='N' ");
            }

            if (count != 0) {
                System.out.println("Bulk auth status updated to S :" + pacsId);
            } else {
                System.out.println("Bulk auth status updatation failed :" + pacsId);
            }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in updateBulkAuthStatusToS for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

        } finally {
            try {
                if (con != null) {
                   // con.commit();
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
    }
     public void updateBulkAuthStatusToS_Exs(String pacsId) {
        Connection con = null;
        Statement qry = null;
        ResultSet rs = null;
        int count = 0;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            count = qry.executeUpdate(" update bulk_acct_mark k set k.status='S',k.send_dt=(select system_date from system_date),k.send_tym=to_date(to_char(SYSTIMESTAMP, 'DD-MON-RRHH24:MI:SS'),'DD-MON-RRHH24:MI:SS') where k.pacs_id= "+pacsId +" and k.status='R'"
                                     +" and k.key_1 in ( select trim(o.add_1) from BULK_ACC_TRICKLEFEED_FILE_auto o where o.status='R' and o.mark_type='E')");
            if (count > 0) {
                count=0;
                count = qry.executeUpdate(" update BULK_ACC_TRICKLEFEED_FILE_auto o set o.status='S' where o.pacs_id="+pacsId+" and o.status='R' and o.mark_type='E' ");
            }

            if (count != 0) {
                System.out.println("Bulk auth status updated to S :" + pacsId);
            } else {
                System.out.println("Bulk auth status updatation failed :" + pacsId);
            }

        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in updateBulkAuthStatusToS for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

        } finally {
            try {
                if (con != null) {
                   // con.commit();
                    con.close();
                }
            } catch (Exception e) {
               // e.printStackTrace();
               System.out.println("Error occurred during connection close.");
            }
        }
    }
//Added For Pacs wise count for Bank Login
      public String  viewBulkMarkAccountsAuth( String pacsId ) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        List<TransactioDetailsBean> tdBeanList = new ArrayList<TransactioDetailsBean>();
        TransactioDetailsBean tdBean = null;
        ObjectMapper objmap = new ObjectMapper();
        String jsonString = null;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            rs = qry.executeQuery("select count(key_1) as Acct_Cnt, pm.pacs_id, pm.pacs_name  from bulk_acct_mark k, pacs_master pm "+
                                     "where pm.pacs_id = k.pacs_id  and pm.pacs_id in (select pacs_id from pacs_master p "+
                                     "where lpad(to_number(p.dccb_code), 2, '0') || lpad(to_number(p.cbs_br_code), 3, '0') in "+
                                     "(select pacs_id from pacs_master pa where pa.pacs_id = '"+pacsId+"' and pacs_id in (select pacs_id " +
                                     " from login_details ld where ld.user_role_id = '201603000008020')) and to_number(pm.dccb_code) = to_number(p.dccb_code) " +
                                     " and lpad(pm.cbs_br_code, 5, '0') = lpad(p.cbs_br_code, 5, '0')) and status = 'R' and k.mark_type = 'N' "+
                                     "and pm.pacs_id <> '"+pacsId+"' group by pm.pacs_id, pm.pacs_name");

         while (rs.next()) {

                tdBean = new TransactioDetailsBean();
                tdBean.setAuthorisedQ(rs.getString("Acct_Cnt")==null?"NA":rs.getString("Acct_Cnt"));
                tdBean.setRejectedQ(rs.getString("pacs_id")==null?"NA":rs.getString("pacs_id"));
                tdBean.setPendingQ(rs.getString("pacs_name")==null?"NA":rs.getString("pacs_name"));
                tdBeanList.add(tdBean);
            }
           jsonString = objmap.writeValueAsString(tdBeanList);
        
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

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

        return jsonString;
    }

    public String  viewBulkMarkAccountsAuth_Exs( String pacsId ) {
        Connection con = null;
        CallableStatement proc = null;
        Statement qry = null;
        String res = null;
        ResultSet rs = null;
        List<TransactioDetailsBean> tdBeanList = new ArrayList<TransactioDetailsBean>();
        TransactioDetailsBean tdBean = null;
        ObjectMapper objmap = new ObjectMapper();
        String jsonString = null;

        try {
            con = DbHandler.getDBConnection();
            qry = con.createStatement();
            rs = qry.executeQuery("select count(key_1) as Acct_Cnt, pm.pacs_id, pm.pacs_name  from bulk_acct_mark k, pacs_master pm "+
                                     "where pm.pacs_id = k.pacs_id  and pm.pacs_id in (select pacs_id from pacs_master p "+
                                     "where lpad(to_number(p.dccb_code), 2, '0') || lpad(to_number(p.cbs_br_code), 3, '0') in "+
                                     "(select pacs_id from pacs_master pa where pa.pacs_id = '"+pacsId+"' and pacs_id in (select pacs_id " +
                                     " from login_details ld where ld.user_role_id = '201603000008020')) and to_number(pm.dccb_code) = to_number(p.dccb_code) " +
                                     " and lpad(pm.cbs_br_code, 5, '0') = lpad(p.cbs_br_code, 5, '0')) and status = 'R' and k.mark_type = 'E' "+
                                     "and pm.pacs_id <> '"+pacsId+"' group by pm.pacs_id, pm.pacs_name");

         while (rs.next()) {

                tdBean = new TransactioDetailsBean();
                tdBean.setAuthorisedQ(rs.getString("Acct_Cnt")==null?"NA":rs.getString("Acct_Cnt"));
                tdBean.setRejectedQ(rs.getString("pacs_id")==null?"NA":rs.getString("pacs_id"));
                tdBean.setPendingQ(rs.getString("pacs_name")==null?"NA":rs.getString("pacs_name"));
                tdBeanList.add(tdBean);
            }
           jsonString = objmap.writeValueAsString(tdBeanList);
       
        } catch (Exception e) {
           // e.printStackTrace();
           // System.out.println("Exception occured  in bulkMarkAccounts for pacs Id :" + pacsId);
           System.out.println("Error occurred during processing.");

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

        return jsonString;
    }
//End Changes
}

