package Controller;

import ServiceLayer.MicrofileProcessingService;
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import LoginDb.DbHandler;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.JSchException;
import java.io.File;

public class CropLoanDisbursementServlet extends HttpServlet {

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

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

        HttpSession session = request.getSession(false);
        MicrofileProcessingService service = new MicrofileProcessingService();
        String filePath = null;
        String fileName = null;
        Session ssn = null;
        JSch jsch = new JSch();
        ChannelSftp sftpChannel = null;
        java.sql.Connection cn = null;
        PreparedStatement ps = null;
        Statement st = null;
        ResultSet rs = null;
        java.sql.Date SYSTEM_DATE = null;

        if (request.getSession().getAttribute("errorMessageSAL") != null) {
            request.getSession().removeAttribute("errorMessageSAL");
        }
        if (request.getSession().getAttribute("successMessageSAL") != null) {
            request.getSession().removeAttribute("errorMessageSAL");
        }

        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                filePath = service.uploadTxtToServer(request);
                System.out.println(filePath);
                //fileName = filePath.substring(filePath.lastIndexOf("\\") + 1); //for test
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1); //for production
                System.out.println("File name after substring is :"+fileName);
            }

            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream input = classLoader.getResourceAsStream("Dao/CL_Disbursement_Vidyasagar.properties");
            System.out.println("ConfigFile read successfully");
            Properties properties = new Properties();
            properties.load(input);

            System.out.println("Going to send file to Job Server via SSH");
            System.out.println("Creating SSH Session: user@host:port |--->" + properties.getProperty("REMOTE_USER") + "@" + properties.getProperty("REMOTE_HOST") + ":" + Integer.parseInt(properties.getProperty("REMOTE_PORT")));
            ssn = jsch.getSession(properties.getProperty("REMOTE_USER"), properties.getProperty("REMOTE_HOST"), Integer.parseInt(properties.getProperty("REMOTE_PORT")));
            ssn.setPassword(properties.getProperty("REMOTE_PASS"));
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            ssn.setConfig(config);
            System.out.println("Establishing Connection...");
            ssn.connect();
            System.out.println("Connection established.");

            System.out.println("Creating SFTP Channel.");
            sftpChannel = (ChannelSftp) ssn.openChannel("sftp");
            sftpChannel.connect();
            System.out.println("SFTP Channel created.");

            try {
                sftpChannel.cd(properties.getProperty("REMOTE_FOLDER_PATH"));  // changing directory
                System.out.println("Current directory is : " + sftpChannel.pwd());
                System.out.println("The file to be pushed is : " + fileName);
                
                sftpChannel.put(properties.getProperty("TEMP_FOLDER_PATH") + fileName, fileName);
                System.out.println("File copied to job server Successfully.");
                File myObj = new File("/home/ec2-user/VCCB_Temp/"+fileName); //deletes the file from local
                myObj.delete();
                System.out.println("Deleted the file: " + myObj.getName()+" from local");

                cn = DbHandler.getDBConnection();
                if (cn != null) {
                    System.out.println("DB Connected..");

                    st = cn.createStatement();
                    rs = st.executeQuery("SELECT SYSTEM_DATE from SYSTEM_DATE");
                    while (rs.next()) {
                        SYSTEM_DATE = rs.getDate("SYSTEM_DATE");
                    }

                    ps = cn.prepareStatement("insert into VCCB_CROP_LOAN_SAL_LOG (SOURCE_FILE_NAME, UPLOAD_DATE, BNK_CODE, STATUS) values (?,?,?,?) ");
                    ps.setString(1, fileName);
                    ps.setDate(2, SYSTEM_DATE);
                    ps.setString(3, "0020");
                    ps.setString(4, "N");
                    ps.executeQuery();
                }
            } catch (SftpException ex) {
                //ex.printStackTrace();
                System.out.println("File could not be pushed to desried directory");
            } catch (SQLException ee) {
                //ee.printStackTrace();
                System.out.println("Data could not be inserted to table");
            } finally {
                st.close();
                rs.close();
                ps.close();
            }
            request.getSession().setAttribute("successMessageSAL", "File Uploaded Successfully");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error occurred during processing.");
            request.getSession().setAttribute("errorMessageSAL", "Request can not be processed");
        } finally {
            System.out.println("Servlet processing done.");
           // response.sendRedirect(request.getHeader("Referer"));
        }

    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
