/*
 * The MIT License
 *
 * Copyright 2016 wensttay.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.github.sistemax.controller;

import com.google.gson.Gson;
import io.github.sistemax.entidades.Evento;
import io.github.sistemax.entidades.Material;
import io.github.sistemax.entidades.Usuario;
import io.github.sistemax.enums.EstadoEvento;
import io.github.sistemax.enums.TipoUsuario;
import io.github.sistemax.model.Fachada;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author wensttay
 */
@WebServlet(name = "desalocar_evento", urlPatterns = {"/desalocar_evento"})
public class DesalocarEventoController extends HttpServlet {

    Fachada fachada;

    /**
     * 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 {
        
        Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
        
        Map<String, String> resultado = new HashMap<>();
        String idEventoString = request.getParameter("id_evento");
        Integer idEvento = Integer.parseInt(idEventoString);
        
        if (idEvento != null) {

            if (fachada == null) {
                fachada = new Fachada();
            }

            Evento ev = fachada.buscarEventoId(idEvento);
            if (ev != null) {
                if (ev.getEstado().equals(EstadoEvento.PENDENTE_DE_ALOCACAO)
                        || ev.getEstado().equals(EstadoEvento.AGENDADO)
                        ){
                    
                    if (usuario.getTipo().equals(TipoUsuario.ASSISTENTE_SALA) 
                        || usuario.getId() == ev.getResponsavel().getId()) {
                
                        if (fachada.desalocarLocalDoEvento(ev.getId())) {
                            List<Material> materiais = fachada.buscarMateriaisDoEvento(ev.getId());

                            for (Material m : materiais) {
                                fachada.retirarMaterialDoEvento(ev.getId(), m.getTombamento());
                            }
                        } else {
                            resultado.put("erro", "O Evento selcionado não está alocado para nenhuma Sala");
                        }
                    } else { 
                        resultado.put("erro", "Você não é o reponsável por este evento ou não possui poderes para realizar esta ação.");
                    }
                } else {
                    resultado.put("erro", "Não é possivel desalocar um evento nesse estado");
                }
            } else {
                resultado.put("erro", "O Evento escolhido não foi encontrado");
            }
        }
        
        String json = new Gson().toJson(resultado);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
        
    }

    // <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 {
        processRequest(request, response);
    }

    /**
     * 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 {
        processRequest(request, response);
    }

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

}
