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

import clases.cCifrado;
import clases.cConexion;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author ian
 */
@WebServlet(name = "sAsociarDietas", urlPatterns = {"/sAsociarDietas"})
public class sAsociarDietas extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            HttpSession sesion = request.getSession();
            
            cConexion conecta = new cConexion();
            conecta.conectar();
            
            cCifrado seguro = new cCifrado();
            seguro.AlgoritmoAES();
            
            int idMedico = 0;
            int idPaciente = 0;
            String idOtro = "";
            int accion = 0;
            int idDieta = 0;
            String idUsr = "";
            String idUsrP = "";
            String quit = "no";
            
//            try{
                idMedico = (Integer)sesion.getAttribute("idMedico");
                idUsr = seguro.encriptar((String)sesion.getAttribute("idUsr"));
                
                idOtro = seguro.encriptar(request.getParameter("idPa"));
                accion = Integer.parseInt(request.getParameter("accion"));
                idDieta = Integer.parseInt(request.getParameter("idDieta"));
                
                ResultSet idP = conecta.spTraerIdPaciente(idOtro);
                if(idP.next()){
                    idPaciente = idP.getInt("idPaciente");
                }
//            }
//            catch(Exception e){
//                System.out.print(e);
//                Map<String, Object> mapa = new HashMap();
//                mapa.put("estado", e);
//                write(response, mapa);
//            }
                
            ResultSet idO = conecta.spGetUsrId(idPaciente);
            if(idO.next()){
                idUsrP = idO.getString("idUsuario");
            }
            
            if(accion == 0){
                quit = "si";
                conecta.actualizarDieta(idUsrP, idDieta, quit);
            }
            
            
            ResultSet rs = conecta.spSetAsociasiones(idPaciente, idMedico, idDieta, idUsr, accion);
            if(rs.next()){
                if(!rs.getString("resultado").equals("no")){
                    Map<String, Object> mapa = new HashMap();
                    mapa.put("estado", "listo");
                    write(response, mapa);
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(sAsociarDietas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(sAsociarDietas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(sAsociarDietas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(sAsociarDietas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void write(HttpServletResponse response, Map<String, Object> map) throws IOException 
    {
        response.setContentType("aplication/json");
        response.setCharacterEncoding("charset=UTF-8");
        response.getWriter().write(new Gson().toJson(map));
    }
}
