/*
 * 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 demojsoncrud.servlets;

import demojsoncrud.beans.UbigeoBean;
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;

/**
 *
 * @author Alonso
 */
public class UbigeoServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("accion");

        if ("listarDepartamento".equals(param)) {
            listarDepartamento(request, response);
        } else if ("listarProvincia".equals(param)) {
            listarProvincia(request, response);
        } else if ("listarDistrito".equals(param)) {
            listarDistrito(request, response);
        }
    }

    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();

        String json = request.getParameter("json");
        JSONObject jsonObject = new JSONObject(json);

        String codigoDepartamento = jsonObject.getString("codigoDepartamento");

        UbigeoBean bean = new UbigeoBean();
        bean.setCodigoDepartamento(codigoDepartamento);

        JSONObject jsonReturn = service.listarProvincia(bean);
        pw.print(jsonReturn);
    }

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

        String json = request.getParameter("json");
        JSONObject jsonObject = new JSONObject(json);

        String codigoDepartamento = jsonObject.getString("codigoDepartamento");
        String codigoProvincia = jsonObject.getString("codigoProvincia");

        UbigeoBean bean = new UbigeoBean();
        bean.setCodigoDepartamento(codigoDepartamento);
        bean.setCodigoProvincia(codigoProvincia);

        JSONObject jsonReturn = service.listarDistrito(bean);
        pw.print(jsonReturn);
    }

}
