package CommunicationServlets;

import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Example servlet showing request headers
 */
public class RequestServlet extends HttpServlet {

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        /*BufferedReader br = request.getReader();
        String buf = br.readLine();
        out.print("Rec:"+buf);*/

        String user = request.getParameter("user");
        String password = request.getParameter("password");
        String ip = request.getRemoteAddr();

        String query = "select * from usuarios where user='" + user + "' and password='" + password + "';";

        Client cliente = new Client();


        if (cliente.remoteAuthentication(query+ip)) {
            out.println("<h1>bienvenido</h1>");
            out.println("<br><br>Sr(a)." + user);
        } else {
            out.println("Usuario o Password incorrecto.");
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        doPost(request, response);
    }
}

class Client {

    public Client() {
    }

    public boolean remoteAuthentication(String input) {
        String output = null;
        try {

            Socket echoSocket = new Socket("localhost", 12345);

            PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

            try {

                out.println(input);
                output = in.readLine();
                if (output.equals("true")) {
                    return true;
                } else {
                    return false;
                }

            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            out.close();
            in.close();
            echoSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
}
