package control;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.servlet.RequestDispatcher;
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 model.CartMod;
import model.MySignature;
import model.RandomNameUploading;

import com.oreilly.servlet.MultipartRequest;

import def.ISendFile;

/**
 * Servlet implementation class CheckOnlinePayment
 */
public class CheckOnlinePayment extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckOnlinePayment() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			File f = new File("cer");
			if (!f.exists()) f.mkdir();
			String folder = getServletContext().getRealPath("cer");
			MultipartRequest mtr = new MultipartRequest(request, folder, 5 * 1024 * 1024, "UTF-8", new RandomNameUploading());
			
			String filen = mtr.getFilesystemName("cername");
			String signedOrder = mtr.getParameter("signedOrder");
			HttpSession session = request.getSession();
			Object obj=session.getAttribute("giohang");
			CartMod giohang=(CartMod)obj;
			
			// Tao du lieu de ky: Danh sach san pham (id), Tong tien
			String data = session.getAttribute("billlist") + "Total: " + Math.round(giohang.Tongtien());
			MySignature ms = new MySignature();
			
			// Xac thuc chu ky
			if (ms.verify(data, signedOrder, folder + "/" + filen)){
				
				// Khoi Tao RMI Client
				Registry reg = LocateRegistry.getRegistry("localhost", 1234);
				Remote obj2 = reg.lookup("cergate");
				ISendFile sendFile = (ISendFile) obj2;
				// End
				
				// Upload Cer
				BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(folder + "/" + filen));
				byte[] buffU = new byte[1024];
				int a;
				sendFile.setFileUp(filen); // Loi neu set path sai
				while((a = fileIn.read(buffU)) != -1){
					sendFile.Upload(buffU, a);
				}
				sendFile.closeOutStream();
				fileIn.close();
				// End
				
				// Verify Certificate
				if (!sendFile.verifyCer(filen)){
					// Lay thong tin Cert. vua tai len
					request.setAttribute("cerinfo", sendFile.getInfoCertificate(filen));
					request.setAttribute("checkmsg", "cer");
					
					// Xoa Cert. luu tam
		            File temp = new File(folder + "/" + filen);
		            temp.delete();
					RequestDispatcher rd = request.getRequestDispatcher("index.jsp?customer=checkout");
		            rd.forward(request, response);
				} else {
					// Lay thong tin Cert. vua tai len
					request.setAttribute("cerinfo", sendFile.getInfoCertificate(filen));
					request.setAttribute("checkmsg", "ok");
					
					// Xoa Cert. luu tam
		            File temp = new File(folder + "/" + filen);
		            temp.delete();
		            
		            // Luu Session Cert. hop le
		            session.setAttribute("validCert", "valid");
		            
					RequestDispatcher rd = request.getRequestDispatcher("index.jsp?customer=checkout");
		            rd.forward(request, response);
				}
				//End
				
			} else {
				request.setAttribute("checkmsg", "sign");
				RequestDispatcher rd = request.getRequestDispatcher("index.jsp?customer=checkout");
	            rd.forward(request, response);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			request.setAttribute("checkmsg", "connect");
			RequestDispatcher rd = request.getRequestDispatcher("index.jsp?customer=checkout");
			rd.forward(request, response);
		}
	}

}
