package demojsoncrud.servlets;

import demojsoncrud.services.UbigeoService;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

public class UbigeoServlet extends HttpServlet {

  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String param = request.getParameter("accion");
    response.setCharacterEncoding("UTF-8");
    if (null != param) {
      switch (param) {
        case "listarDepartamento":
          listarDepartamento(request, response);
          break;
        case "listarProvincia":
          listarProvincia(request, response);
          break;
        case "listarDistrito":
          listarDistrito(request, response);
          break;
        default:
          response.setContentType("application/json");
          PrintWriter pw = response.getWriter();
          JSONObject respuesta = new JSONObject();
          respuesta
            .put("status", false)
            .put("message", "No existe la url solicitada.")
            .put("data", "");
          pw.print(respuesta);
          break;
      }
    }
  }

  private void listarDepartamento(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    PrintWriter pw = response.getWriter();
    UbigeoService service = new UbigeoService();
    JSONObject json = service.listarDepartamento();
    pw.print(json);
  }

  private void listarProvincia(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    PrintWriter pw = response.getWriter();
    UbigeoService service = new UbigeoService();
    JSONObject datos = new JSONObject(request.getParameter("json"));
    JSONObject respuesta = service.listarProvincia(datos);
    pw.print(respuesta);
  }

  private void listarDistrito(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    PrintWriter pw = response.getWriter();
    UbigeoService service = new UbigeoService();
    JSONObject datos = new JSONObject(request.getParameter("json"));
    JSONObject respuesta = service.listarDistrito(datos);
    pw.print(respuesta);
  }

}
