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

import Dao.MicroFileProcessingDao;
import DataEntryBean.MicroFileAccountDetBean;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import com.jcraft.jsch.*;

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

    private static final char DEFAULT_SEPARATOR = '|';
    private static final char COMMA_SEPARATOR = ',';

    public StringBuilder downloadCsvFile(String pacsId, String agentId) {
        ArrayList<MicroFileAccountDetBean> accountList = null;
        ArrayList<String> accountListParam = null;
        MicroFileProcessingDao microDao = new MicroFileProcessingDao();
        accountList = microDao.getAccountDetails(pacsId, agentId);
        StringBuilder csvOutput = null;

        try {
            if (accountList != null && accountList.size() != 0) {

                accountListParam = new ArrayList<String>();

                //Header removed from gl14.test
//            accountListParam.add("ACC_NO");
//            accountListParam.add("ACCT_NAME");
//            accountListParam.add("PROD_NAME");
//            //accountListParam.add("PROD_TYPE");column removed from csv as same is omitted  for time being -- 29/05/2018 Rajdip
//            accountListParam.add("ADDRESS_1");
//            accountListParam.add("ADDRESS_2");
//            //accountListParam.add("ADDRESS_3");column removed from csv as same is omitted  for time being -- 29/05/2018 Rajdip
//            accountListParam.add("PIN_CODE");//pincode blank
//            accountListParam.add("AVAIL_BAL");
                csvOutput = new StringBuilder();
                // writeLine(csvOutput, accountListParam, DEFAULT_SEPARATOR); // for header write
                for (MicroFileAccountDetBean accountdetail : accountList) {
                    //writer = new FileWriter(csvFile);
                    accountListParam = new ArrayList<String>();
                    accountListParam.add(accountdetail.getAccountCode());
                    accountListParam.add(accountdetail.getAccountName());
                    accountListParam.add(accountdetail.getProdName());
                    accountListParam.add(accountdetail.getProdType());//Hardcoded as deposit
                    accountListParam.add(accountdetail.getAdd1());
                    accountListParam.add(accountdetail.getAdd2());
                    accountListParam.add(accountdetail.getAdd3());//column removed from csv as sae is omitted  for time being -- 29/05/2018 Rajdip
                    accountListParam.add("NA");//pincode field not presnet in db . Added NA  09072018
                    //account open date 29062018
                    accountListParam.add(accountdetail.getAccntOpenDate());
                    accountListParam.add(String.valueOf(accountdetail.getAvailBal()));
                    //maturity date
                    accountListParam.add(accountdetail.getAccntMaturityDate());
                    accountListParam.add(accountdetail.getGuardianName());
                    writeLine(csvOutput, accountListParam, DEFAULT_SEPARATOR);
                    accountListParam = null;
                }
            } else {
                return csvOutput;
            }

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured making csv balance file  for pacs :" + pacsId);
        } finally {
            System.out.println("Processing done.");
        }
        return csvOutput;
    }

    private static void writeLine(StringBuilder w, List<String> values, char separators) throws IOException {

        boolean first = true;
        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            sb.append(value);

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());

    }

    public MicroFileAccountDetBean readAndInsertFromCSV(String pacsId, String csvFile, String tellerId) {
        //String csvFile = "/Users/mkyong/csv/country.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = String.valueOf(DEFAULT_SEPARATOR);
        MicroFileAccountDetBean accountDetail = null;
        ArrayList<MicroFileAccountDetBean> accountDetailsList = new ArrayList<MicroFileAccountDetBean>();
        MicroFileProcessingDao dao = new MicroFileProcessingDao();
        int result = 0;
        int firstTimeCount = 0;
        MicroFileAccountDetBean fileResultObject = new MicroFileAccountDetBean();
        try {
          //  br = new BufferedReader(new FileReader(csvFile));
            //while ((line = br.readLine()) != null) {

                try {// use | as separator
                    if (firstTimeCount != 0) {
                        String[] accountDetails = line.split("\\" + cvsSplitBy);
                        accountDetail = new MicroFileAccountDetBean();
                        accountDetail.setAccountCode(accountDetails[0]);
                        accountDetail.setDrTotal(Double.parseDouble(accountDetails[4]));
                        accountDetail.setAccountName(accountDetails[2]);// 3rd column of the csv as total credit is omitted  for time being -- 29/06/2018 Rajdip
                        accountDetail.setAvailBal(Double.parseDouble(accountDetails[3])); //4th column of the csv as to tal credit is omitted  for time being -- 29/06/2018 Rajdip
                        accountDetail.setCrTotal(Double.parseDouble(accountDetails[1]));
                        accountDetailsList.add(accountDetail);
                        accountDetail = null;
                    }
                    firstTimeCount++;
                } catch (Exception ex) {
                    // ex.printStackTrace();
                    System.out.println("Exception occured reading EOD balance file one row for pacs :" + pacsId);
                }
            }
            result = dao.insertIntoHandbillTemp(accountDetailsList, pacsId, tellerId);

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading EOD balance file for pacs :" + pacsId);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                    System.out.println("Error occurred during processing.");
                }
            }
        }
        fileResultObject.setSuccessfulRecords(result);
        fileResultObject.setTotalRecords(accountDetailsList.size());
        return fileResultObject;
    }

    public String uploadCSVToServer(HttpServletRequest request, String pacsId) {
        String contentType = request.getContentType();
        String filePath = null;
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream input = classLoader.getResourceAsStream("Dao/BulkMarkSTB.properties");
            Properties properties = new Properties();
            properties.load(input);

            String APPLICATION_FOLDER_PATH = properties.getProperty("APPLICATION_FOLDER_PATH");
            //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
               // DataInputStream in = new DataInputStream(request.getInputStream());
                //we are taking the length of Content type data
                //int formDataLength = request.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
                //this loop converting the uploaded file into byte code
                while (totalBytesRead < formDataLength) {
                 //   byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += byteRead;
                }
                String file = new String(dataBytes);
                //for saving the file name
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1, contentType.length());
                int pos;
                //extracting the index of file
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                // File fileNew = new File("C:/D/" + saveFile + String.valueOf(System.currentTimeMillis()));
                // File fileNew = new File("/" + saveFile + String.valueOf(System.currentTimeMillis()));
                File fileNew = new File(APPLICATION_FOLDER_PATH + saveFile + String.valueOf(System.currentTimeMillis()));
                // creating a new file with the same name and writing the content in new file
                FileOutputStream fileOut = new FileOutputStream(fileNew);
                fileOut.write(dataBytes, startPos, (endPos - startPos));
                fileOut.flush();
                fileOut.close();
                filePath = fileNew.getAbsolutePath();
            }
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading csv from client for pacs :" + pacsId);
        } finally {
            System.out.println("Processing done.");
        }
        return filePath;
    }

    public String uploadTxtToServer(HttpServletRequest request) {
        String contentType = request.getContentType();
        String filePath = null;
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream input = classLoader.getResourceAsStream("Dao/CL_Disbursement_Vidyasagar.properties");
            Properties properties = new Properties();
            properties.load(input);

            String TEMP_FOLDER_PATH = properties.getProperty("TEMP_FOLDER_PATH");
            //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
              //  DataInputStream in = new DataInputStream(request.getInputStream());
                //we are taking the length of Content type data
               // int formDataLength = request.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
                //this loop converting the uploaded file into byte code
                while (totalBytesRead < formDataLength) {
                   // byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += byteRead;
                }
                String file = new String(dataBytes);
                //for saving the file name
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1, contentType.length());
                int pos;
                //extracting the index of file
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                File fileNew = new File(TEMP_FOLDER_PATH + saveFile);
                // creating a new file with the same name and writing the content in new file
                FileOutputStream fileOut = new FileOutputStream(fileNew);
                fileOut.write(dataBytes, startPos, (endPos - startPos));
                fileOut.flush();
                fileOut.close();
                filePath = fileNew.getAbsolutePath();
            }
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading txt from client for pacs :");
        } finally {
            System.out.println("Processing done.");
        }
        return filePath;
    }

    public String uploadPrtToServer(HttpServletRequest request, String pacsId) {
        String contentType = request.getContentType();
        String filePath = null;
        try {
            //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
              //  DataInputStream in = new DataInputStream(request.getInputStream());
                //we are taking the length of Content type data
               // int formDataLength = request.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
                //this loop converting the uploaded file into byte code
                while (totalBytesRead < formDataLength) {
                  //  byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += byteRead;
                }
                String file = new String(dataBytes);
                //for saving the file name
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1, contentType.length());
                int pos;
                //extracting the index of file
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                File fileNew = new File("/" + saveFile + String.valueOf(System.currentTimeMillis()));
                // creating a new file with the same name and writing the content in new file
                FileOutputStream fileOut = new FileOutputStream(fileNew);
                fileOut.write(dataBytes, startPos, (endPos - startPos));
                fileOut.flush();
                fileOut.close();
                filePath = fileNew.getAbsolutePath();
            }
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading csv from client for pacs :" + pacsId);
        } finally {
            System.out.println("Processing done.");
        }
        return filePath;
    }

    public String readAndInsertFromPRT(String pacsId, String prtFile, String tellerId) {
        BufferedReader br = null;
        String line = "";
        String accNo = "";
        String cbsAccNo = "";
        String outMsg = "";
        List<String> accntdetailsList = new ArrayList<String>();
        MicroFileProcessingDao dao = new MicroFileProcessingDao();

        try {
           // br = new BufferedReader(new FileReader(prtFile));
            try {
               // while ((line = br.readLine()) != null) {

                    if (!line.isEmpty() && line.length() == 146) {
                        accNo = line.substring(129);
                        cbsAccNo = line.substring(75, 89);
                        //cbsAccNo = cbsAccNo.substring(0, 11).concat(String.valueOf(cbsAccNo.charAt(12)));
                        cbsAccNo = cbsAccNo.replace("-", "");
                        cbsAccNo = cbsAccNo.replace(" ", "");
                        accntdetailsList.add(accNo + ":" + cbsAccNo);
                        System.out.println(accNo + ":" + cbsAccNo);
                    }
                    if (!line.isEmpty() && line.length() == 129) {
                        accNo = line.substring(112);
                        cbsAccNo = line.substring(74, 89);
                        //cbsAccNo = cbsAccNo.substring(0, 11).concat(String.valueOf(cbsAccNo.charAt(12)));
                        cbsAccNo = cbsAccNo.replace("-", "");
                        cbsAccNo = cbsAccNo.replace(" ", "");
                        accntdetailsList.add(accNo + ":" + cbsAccNo);
                        System.out.println(accNo + ":" + cbsAccNo);
                    }

                }
            } catch (Exception e) {
                // e.printStackTrace();
                System.out.println("Error occurred during processing.");
            } finally {
                System.out.println("Processing done.");
            }

            if (accntdetailsList.size() > 0) {
                outMsg = dao.insertBulkAccMap(accntdetailsList, pacsId, tellerId);
            }

            if (outMsg.isEmpty()) {
                outMsg = "Error during bulk account mapping";
            }

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Error occurred during processing.");
        } finally {
            System.out.println("Processing done.");
        }

        return outMsg;
    }

//    public String checkActionTag(HttpServletRequest request, Object obj)
//    {
//        String action = null;
//        try {
//        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//            DiskFileItemFactory factory = new DiskFileItemFactory();
//
//            // Configure a repository (to ensure a secure temp location is used)
//            ServletContext servletContext = obj.getServletConfig().getServletContext();
//            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
//            factory.setRepository(repository);
//
//            // Create a new file upload handler
//            ServletFileUpload upload = new ServletFileUpload(factory);
//
//            // Parse the request
//            List<FileItem> items = upload.parseRequest(request);
//            Iterator<FileItem> iter = items.iterator();
//            while (iter.hasNext()) {
//                FileItem item = iter.next();
//
//                if (item.isFormField() && item.getFieldName().equalsIgnoreCase("actionTag")) {
//                     action = item.getString();
//                     break;
//                }
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return action;
//    }
    public String readAndInsertFromCSVForBulk(String pacsId, String csvFile, String tellerId) {
        //String csvFile = "/Users/mkyong/csv/country.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = String.valueOf(COMMA_SEPARATOR);
        MicroFileAccountDetBean accountDetail = null;
        ArrayList<MicroFileAccountDetBean> accountDetailsList = new ArrayList<MicroFileAccountDetBean>();
        MicroFileProcessingDao dao = new MicroFileProcessingDao();
        String result = null;
        int firstTimeCount = 0;
        MicroFileAccountDetBean fileResultObject = new MicroFileAccountDetBean();
        try {
           // br = new BufferedReader(new FileReader(csvFile));
           // while ((line = br.readLine()) != null) {

                try {// use | as separator
                    if (firstTimeCount != 0) {
                        String[] accountDetails = line.split("\\" + cvsSplitBy);
                        accountDetail = new MicroFileAccountDetBean();
                        accountDetail.setTxnType(accountDetails[0]);
                        accountDetail.setCrTotal(Double.parseDouble(accountDetails[3]));
                        accountDetail.setFromAccBulk((accountDetails[1]));
                        accountDetail.setToAccBulk((accountDetails[2]));
                        accountDetail.setMessage(accountDetails[4]);// narration in bulk file
                        accountDetailsList.add(accountDetail);
                        accountDetail = null;
                    }
                    firstTimeCount++;
                } catch (Exception ex) {
                    // ex.printStackTrace();
                    System.out.println("Exception occured reading Bulk  file one row for pacs :" + pacsId);
                }
            }
            result = dao.insertIntoBulkFileDetails(accountDetailsList, pacsId, tellerId, csvFile);

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading Bulk file for pacs :" + pacsId);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                    System.out.println("Error occurred during connection close.");
                }
            }
        }

        return result;
    }

    public String readAndInsertFromCSVForAccountRenewBulk(String pacsId, String csvFile, String tellerId) {
        //String csvFile = "/Users/mkyong/csv/country.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = String.valueOf(COMMA_SEPARATOR);
        MicroFileAccountDetBean accountDetail = null;
        ArrayList<MicroFileAccountDetBean> accountDetailsList = new ArrayList<MicroFileAccountDetBean>();
        MicroFileProcessingDao dao = new MicroFileProcessingDao();
        String result = null;
        int firstTimeCount = 0;
        MicroFileAccountDetBean fileResultObject = new MicroFileAccountDetBean();
        try {
           // br = new BufferedReader(new FileReader(csvFile));
            //while ((line = br.readLine()) != null) {
                try {// use | as separator
                    if (firstTimeCount != 0) {
                        String[] accountDetails = line.split("\\" + cvsSplitBy);
                        accountDetail = new MicroFileAccountDetBean();

                        accountDetail.setToAccBulk((accountDetails[0]));//kcc account
                        accountDetail.setLimit(accountDetails[1]);//limit
                        accountDetail.setAccntMaturityDate(accountDetails[2]); // limit expiry date
                        accountDetailsList.add(accountDetail);
                        accountDetail = null;
                    }
                    firstTimeCount++;
                } catch (Exception ex) {
                    // ex.printStackTrace();
                    System.out.println("Exception occured reading Account Renew Bulk  file one row for pacs :" + pacsId);
                }
            }
            result = dao.insertIntoBulkFileDetailsAccountRenewal(accountDetailsList, pacsId, tellerId, csvFile);

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading Account Renew Bulk file for pacs :" + pacsId);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                    System.out.println("Error occurred during processing.");
                }
            }
        }

        return result;
    }

    public String readAndInsertFromCSVForBankKCC(String pacsId, String csvFile, String tellerId) {
        //String csvFile = "/Users/mkyong/csv/country.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = String.valueOf(COMMA_SEPARATOR);
        MicroFileAccountDetBean accountDetail = null;
        ArrayList<MicroFileAccountDetBean> accountDetailsList = new ArrayList<MicroFileAccountDetBean>();
        MicroFileProcessingDao dao = new MicroFileProcessingDao();
        String result = null;
        int firstTimeCount = 0;
        MicroFileAccountDetBean fileResultObject = new MicroFileAccountDetBean();
        try {
           // br = new BufferedReader(new FileReader(csvFile));
           // while ((line = br.readLine()) != null) {
                try {// use | as separator
                    if (firstTimeCount != 0) {
                        String[] accountDetails = line.split("\\" + cvsSplitBy);
                        accountDetail = new MicroFileAccountDetBean();

                        accountDetail.setToAccBulk((accountDetails[0]));//kcc account
                        accountDetail.setLimit(accountDetails[1]);//limit
                        accountDetail.setAccntMaturityDate(accountDetails[2]); // limit expiry date
                        accountDetailsList.add(accountDetail);
                        accountDetail = null;
                    }
                    firstTimeCount++;
                } catch (Exception ex) {
                    // ex.printStackTrace();
                    System.out.println("Exception occured reading Account Renew Bulk  file one row for pacs :" + pacsId);
                }
            }
            result = dao.insertIntoBankPostKCCRenewal(accountDetailsList, pacsId, tellerId, csvFile);

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("Exception occured reading Account Renew Bulk file for pacs :" + pacsId);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                    System.out.println("Error occurred during processing.");
                }
            }
        }

        return result;
    }
}
