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

import DataEntryBean.kycCreationBean;
import LoginDb.DbHandler;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author TCS
 */
public class kycCreationServlet extends HttpServlet {

    private boolean isMultipart;
    private int maxFileSize = 5000 * 1024;
    private int maxMemSize = 4 * 1024;
    private String uploadPathMain;
    private String uploadPath;
    private File file;
    private int fileUpload = 0;
    private File renameFile;
    private boolean t;
    private boolean s;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet kycCreationServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet kycCreationServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

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

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

        HttpSession session = request.getSession(false);
        Connection con = null;
        CallableStatement proc = null;
        Statement statement = null;
        ResultSet rs = null;
        String message = "";
        String PhotouploadedFlag = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        String handle_id = request.getParameter("handle_id");
        String lastPhotoName = (String) session.getAttribute("lastPhotoName");
        String sigPhotoName = (String) session.getAttribute("sigPhotoName");
        //System.out.println(lastPhotoName);

        kycCreationBean okycCreationBean = new kycCreationBean();
        try {
          //  BeanUtils.populate(okycCreationBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(kycCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error occurred during processing.");
        }

        ServletContext servletContext = getServletContext();
       // uploadPathMain = servletContext.getRealPath(File.separator);
        uploadPath = uploadPathMain + "/" + "UploadedFiles";
        File destinationDir = new File(uploadPath);

        if (!destinationDir.exists()) {
            destinationDir.mkdir();
        }

        if (!lastPhotoName.isEmpty()) {
            File f = null;
            File f1 = null;
            try {
                // create new File objects
                f = new File(uploadPath + File.separator + lastPhotoName);
                f1 = new File(uploadPath + File.separator + okycCreationBean.getCif() + ".jpg");

                // rename file
                t = f.renameTo(f1);
            } catch (Exception e) {
                // if any error occurs
               // e.printStackTrace();
               System.out.println("Error occurred during processing.");
            }
        }

        //For Signature
                if (!sigPhotoName.isEmpty()) {
                    File f = null;
                    File f1 = null;
                    try {
                        // create new File objects
                        f = new File(uploadPath + File.separator + sigPhotoName);
                        f1 = new File(uploadPath + File.separator + "sig-" + okycCreationBean.getCif() + ".jpg");

                        // rename file
                        s = f.renameTo(f1);
                    } catch (Exception e) {
                        // if any error occurs
                       // e.printStackTrace();
                       System.out.println("Error occurred during processing.");
                    }
                }

        /*
        try {


        //For Photo Upload Starts Here

        // Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(request);
        System.out.println("Check that we have a file upload request :" + isMultipart);
        response.setContentType("text/html");
        if (!isMultipart) {
        message = "Photo Not in proper Format";
        request.setAttribute("message", message);
        request.getRequestDispatcher("/kycCreation.jsp").forward(request, response);
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        Iterator itr = fileItems.iterator();

        Iterator itr2 = fileItems.iterator();
        while (itr2.hasNext()) {
        FileItem fi2 = (FileItem) itr2.next();

        BeanUtils.setProperty(okycCreationBean, fi2.getFieldName(), fi2.getString());

        }
        con = DbHandler.getDBConnection();
        try {
        statement = con.createStatement();
        rs = statement.executeQuery("select d.photo_uploaded from kyc_details d where d.cif_no = '" + okycCreationBean.getCif() + "'");
        while (rs.next()) {
        PhotouploadedFlag = rs.getString(1);
        }

        statement.close();
        con.close();
        } catch (Exception e) {
        }
        while (itr.hasNext()) {
        FileItem fi = (FileItem) itr.next();

        if (!fi.isFormField()) {
        if (!fi.getFieldName().equalsIgnoreCase("")) {
        // Get the uploaded file parameters
        String fieldName = fi.getFieldName();
        String fileName = fi.getName();
        String contentType = fi.getContentType();
        boolean isInMemory = fi.isInMemory();
        long sizeInBytes = fi.getSize();
        //check if the uploaded file is an excel file
        String fileExtention = fileName.substring(fileName.length() - 3, fileName.length()).toLowerCase();
        if (!fileExtention.equals("jpg")) {
        //return to jsp with an error message
        message = "Uploaded Photo is not in jpg Format";
        throw new Exception();
        } else {

        ServletContext servletContext = getServletContext();
        uploadPathMain = servletContext.getRealPath(File.separator);
        uploadPath = uploadPathMain + "/" + "UploadedFiles";
        File destinationDir = new File(uploadPath);

        if (!destinationDir.exists()) {
        destinationDir.mkdir();
        }

        // Write the file
        if (fileName.lastIndexOf("\\") >= 0) {
        file = new File(uploadPath
        + fileName.substring(fileName.lastIndexOf("\\")));
        } else {
        file = new File(uploadPath + File.separator
        + fileName.substring(fileName.lastIndexOf("\\") + 1));
        }

        File checkfileExists = new File(uploadPath + File.separator + okycCreationBean.getCif() + ".jpg");
        //System.out.println("checking if same file exists or not " + checkfileExists.exists());

        if (checkfileExists.exists() && PhotouploadedFlag.equalsIgnoreCase("Y")) {
        message = "Photograph for this customer is already registered!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("/kycCreation.jsp").forward(request, response);
        } else {
        fi.write(file);
        renameFile = new File(uploadPath + File.separator + okycCreationBean.getCif() + ".jpg");
        file.renameTo(renameFile);
        fileUpload = 1;
        }

        }

        } */

        try {
            con = DbHandler.getDBConnection();
            try {
                proc = con.prepareCall("{ call operations.create_kyc_details(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");
            } catch (SQLException ex) {
               // Logger.getLogger(kycCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            proc.setString(1, okycCreationBean.getCif());
            proc.setString(2, okycCreationBean.getcType());
            proc.setString(3, okycCreationBean.getLinkedAccount());
            proc.setString(4, okycCreationBean.getTittle());
            proc.setString(5, okycCreationBean.getfName());
            proc.setString(6, okycCreationBean.getmName());
            proc.setString(7, okycCreationBean.getlName());
            proc.setString(8, okycCreationBean.getgName());
            proc.setString(9, okycCreationBean.getAdd1());
            proc.setString(10, okycCreationBean.getAdd2());
            proc.setString(11, okycCreationBean.getAdd3());
            proc.setString(12, okycCreationBean.getDistname());
            proc.setString(13, okycCreationBean.getCityname());
            proc.setString(14, okycCreationBean.getStatename());
            proc.setString(15, okycCreationBean.getDob());
            proc.setString(16, okycCreationBean.getGender());
            proc.setString(17, okycCreationBean.getmNumber());
            proc.setString(18, okycCreationBean.getIdType());
            proc.setString(19, okycCreationBean.getIdNumber());
            proc.setString(20, okycCreationBean.getIdIssueDate());
            proc.setString(21, okycCreationBean.getIdIssueAt());
            proc.setString(22, "Create");
            proc.setString(23, pacsId);
            proc.setString(24, okycCreationBean.getBlock());
            proc.setString(25, okycCreationBean.getEmailId());


            proc.registerOutParameter(25, java.sql.Types.VARCHAR);
            if (!t) {
                proc.setString(26, "");
            } else {
                proc.setString(26, okycCreationBean.getCif() + ".jpg");
            }
            //For Signature
            if (!s) {
                proc.setString(27, "");
            } else {
                proc.setString(27, "sig-" + okycCreationBean.getCif() + ".jpg");
            }

            proc.setString(28, okycCreationBean.getReligion());
            proc.setString(29, okycCreationBean.getCaste());

            proc.execute();

           // message = proc.getString(25);
            //generatedCIF = okycCreationBean.getCif();

        } catch (SQLException ex) {
           // Logger.getLogger(kycCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           // System.out.println(ex.toString());
           System.out.println("Error occurred during processing.");
            //if (fileUpload == 1) {
            //   renameFile.delete();
            // }

        } finally {
            try {
                proc.close();
            } catch (SQLException e) {
               // System.out.println(e.toString());
               System.out.println("Error occurred during proc close.");
            }
            try {
                con.close();
            } catch (SQLException ex) {
               // Logger.getLogger(kycCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               // System.out.println(ex.toString());
               System.out.println("Error occurred during connection close.");
            }

            request.setAttribute("message", message);
            request.getRequestDispatcher("/kycCreation.jsp").forward(request, response);
        }


    }

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