package sac.gui.handler;

import sac.fachada.SACFachada;
import sac.pessoa.UsuarioComum;
import sac.pessoa.juridica.FiltroBuscaPessoaJuridica;
import sac.medicamento.Medicamento;
import sac.medicamento.MedicamentoJaCadastradoException;
import sac.medicamento.MedicamentoNaoCadastradoException;
import sac.medicamento.Apresentacao;

import sac.doenca.DoencaNaoCadastradaException;
import sac.doenca.Doenca;

import sac.cid.CID;

import sac.pessoa.juridica.PessoaJuridica;

import sac.droga.Droga;
import sac.droga.DrogaNaoCadastradaException;

import sac.exception.ItemJaCadastradoException;
import sac.exception.ItemNaoCadastradoException;
import sac.exception.NullArgumentException;
import sac.exception.InvalidArgumentException;
import sac.exception.NullArgumentException;

import sac.persistencia.PersistenceException;
import sac.persistencia.OID;

import sac.gui.bean.MedicamentoBean;
import sac.gui.bean.DrogaBean;
import sac.gui.bean.DoencaBean;
import sac.gui.bean.PessoaJuridicaBean;
import sac.gui.bean.CampoInvalidoException;
import sac.gui.bean.LoginUsuarioBean;

import java.io.IOException;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.sql.SQLException;
import java.util.Vector;
import java.util.Set;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

/**
 * Handler para o formulário de login no sistema.
 *
 */
public class CadastroMedicamentoHandler extends SACHandler {
    private final static int QTD_MAX_SUBMISSOES_GRATIS = 5;
    private static final int SIZE_RESP = 10;
    private static final String OPERACAO_CADASTRO = "InsercaoOperation";
    private static final String OPERACAO_FILL_FROM = "FillFormOperation";
    private static final String OPERACAO_ALTERACAO = "AlteracaoOperation";
    private static final String OPERACAO_OBTEM_MEDICAMENTO = "ObtemMedicamentoOperation";
    private static final String CONSULTAS_MEDICAMENTO = "ConsultasMedicamentoOperation";
    private static final String CONSULTA_MEDICAMENTO_NOME = "ConsultaMedicamentoNomeOperation";
    private static final String CONSULTA_MEDICAMENTO_DROGA = "ConsultaMedicamentoDrogaOperation";
    private static final String CONSULTA_MEDICAMENTO_DOENCA = "ConsultaMedicamentoDoencaOperation";
    private static final String CONSULTA_MEDICAMENTO_LABORATORIO = "ConsultaMedicamentoLaboratorioOperation";
    private static final String CONSULTA_MEDICAMENTO_CID = "ConsultaMedicamentoCIDOperation";

    private static final String URL_OPERACAO_OK = "/jsp/operacaoOk.jsp";
    private static final String URL_CADASTRO_MEDICAMENTO = "/jsp/cadastro_medicamento.jsp";
    private static final String URL_ALTERACAO_MEDICAMENTO = "/jsp/alteracao_medicamento.jsp";
    private static final String URL_MEDICAMENTO_ERRO = "/jsp/erroOperacao.jsp";
    private static final String URL_CONSULTA_MEDICAMENTO = "/jsp/consulta_medicamento.jsp";
//    private static final String URL_RESPONSE_CONSULTA_MEDICAMENTO = "/jsp/response_consulta_medicamento.jsp";
    private static final String URL_OBTER_MEDICAMENTO = "/jsp/exibirMedicamento.jsp";

    /** Constantes utilizadas no Request desse Handler.*/
    private static  final String MEDICAMENTO_BEAN_REQUEST = "medicamentoBean";
    public static final String MEDICAMENTO_ERRO = "mensagemErro";

    /** Constantes que definem os nomes dos Inputs do Form. */
    private static final String OID_INPUT = "oid";
    private static final String NOME_INPUT = "nome";
    private static final String APRESENTACAO_INPUT = "apresentacao";
    private static final String LABORATORIO_INPUT = "laboratorios";
    private static final String INDICACOES_INPUT = "indicacoes";
    private static final String CONTRA_INDICACOES_INPUT = "contraIndicacoes";
    private static final String DROGA_PRINCIPAL_INPUT = "drogaPrincipal";
    private static final String DROGAS_SECUNDARIAS_INPUT = "drogasSecundarias";
    private static final String DOENCAS_RELACIONADAS_INPUT = "doencasRelacionadas";
    private static final String PRECO_VAREJO_INPUT = "precoVarejo";
    private static final String PRECO_ATACADO_INFERIOR_INPUT = "precoAtacadoInferior";
    private static final String PRECO_ATACADO_SUPERIOR_INPUT = "precoAtacadoSuperior";


    /** Guarda o mapeamento (operacao, Handler)   */
    protected Map functionImplementers;

    /** Guarda o último handler solicitado. */
    protected SACHandler currentImplementer;

    /** Guarda a última operação solicitada. */
    protected String currentFunction;

    /** Creates new MenuHandler */
    public CadastroMedicamentoHandler() {
        super();
        this.functionImplementers = new Hashtable();
        this.functionImplementers.put(OPERACAO_CADASTRO, new InsercaoMedicamentoHandler());
        this.functionImplementers.put(OPERACAO_ALTERACAO, new AlteracaoMedicamentoHandler());
        this.functionImplementers.put(OPERACAO_FILL_FROM, new FillFormHandler());
        this.functionImplementers.put(OPERACAO_OBTEM_MEDICAMENTO, new ObtemMedicamentoHandler());
        this.functionImplementers.put(CONSULTAS_MEDICAMENTO, new ConsultasMedicamentoHandler());
        this.functionImplementers.put(CONSULTA_MEDICAMENTO_NOME, new ConsultaMedicamentoNomeHandler());
        this.functionImplementers.put(CONSULTA_MEDICAMENTO_DOENCA, new ConsultaMedicamentoDoencaHandler());
        this.functionImplementers.put(CONSULTA_MEDICAMENTO_DROGA, new ConsultaMedicamentoDrogaHandler());
        this.functionImplementers.put(CONSULTA_MEDICAMENTO_LABORATORIO, new ConsultaMedicamentoLaboratorioHandler());
    }

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @param fachada fachada do Sistema
     * @return String a url do form a ser retornado
     */
    public String processRequest(HttpServletRequest request, HttpServletResponse response, SACFachada sacFachada)
    throws ServletException, IOException {
        String functionName = request.getParameter(SACHandler.FUNCTION_ID);
        String res = null;
        Object handler;
        if (functionName.equals(currentFunction)) {
            handler = currentImplementer;
        } else {
            handler = functionImplementers.get(functionName);
        }
        if (handler != null) {
            res = ((SACHandler) handler).processRequest(request, response, sacFachada);
            this.currentFunction = functionName;
            this.currentImplementer = (SACHandler) handler;
        } else {
            System.out.println("Nao conseguiu obter o handler " + functionName);
        }
        System.out.println("Saiu do processRequest inicial");
        return res;
    }

    /**
     * Handler para a operacao de cadastro de Medicamento no sistema.
     */
    private class InsercaoMedicamentoHandler extends SACHandler {

        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
         * @param fachada fachada do Sistema
         * @return String a url do form a ser retornado
         */
         public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {


            String res = "";
            Medicamento medicamento = null;
            MedicamentoBean bean = new MedicamentoBean();
            List drogas = null, doencas = null, apres = null, pessoas = null;
            Object obj;
            PessoaJuridicaBean PJBean;
            LoginUsuarioBean user = null;

            try {
            // !!! getSession vai ser null qd nao tiver logado, tratar isto
            user = (LoginUsuarioBean) request.getSession(false).
                                    getAttribute("usuario");
            if(user!=null) {
                if(user.getStatus() == sac.pessoa.UsuarioComum.STATUS_OPERADOR ||
                   user.getStatus() == sac.pessoa.UsuarioComum.STATUS_PESSOA_JURIDICA){

                    if(user.getStatus() == sac.pessoa.UsuarioComum.STATUS_PESSOA_JURIDICA){
                        obj = fachada.procuraUsuario(user.getLogin(), user.getStatus());
                        if (obj instanceof PessoaJuridica) {
                            System.out.println("é pessoa juridica!");
                            PJBean = new PessoaJuridicaBean();
                            PessoaJuridica pj = (PessoaJuridica) obj;
                            PJBean.setCnpj(pj.getCnpj());
                            PJBean.setNome(pj.getNome());
                            PJBean.setHomePage(pj.getHomePage());
                            System.out.println("PJ: "+ PJBean.getNome());
                        } else {
                            System.out.println("MedicamentoHandler.FillformHandler - objeto nao é PJ");
                            throw new PersistenceException("objeto nao é pessoa juridica");
                        }
                    }

                    drogas = fachada.obtemDrogas();
                    doencas = fachada.listarDoencas();
                    apres = fachada.getApresentacoes();

                    pessoas = fachada.listarPessoasJuridicas();
// <provisorio>
/*                pessoas = new Vector();
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/
// <\provisorio>

                    bean = getMedicamentoBeanFromRequest(request, fachada);
                    bean.validaBean();
                    medicamento = getMedicamentoFromBean(bean, fachada);

                    System.out.println("Cadastrando medicamento");
                    fachada.cadastrarMedicamento(medicamento);
                    System.out.println("Medicamento " + medicamento.getNome() + " cadastrado");
                    res = URL_OPERACAO_OK;
                    System.out.println("Retornando a URL="+res);
                } else{
                    request.setAttribute(MEDICAMENTO_ERRO,
                          "Precisa ser Operador para realizar essa operacao!");
                    res = URL_MEDICAMENTO_ERRO;
                }
            } else{
                    request.setAttribute(MEDICAMENTO_ERRO,
                          "Você precisa estar logado!");
                    res = URL_MEDICAMENTO_ERRO;
            }

            } catch(CampoInvalidoException exc) {
                exc.printStackTrace();
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST,bean);
                request.setAttribute("drogas", drogas);
                request.setAttribute("doencas", doencas);
                request.setAttribute("apres", apres);
                request.setAttribute("labs", pessoas);
                request.setAttribute("status", String.valueOf(user.getStatus()));
                res = URL_CADASTRO_MEDICAMENTO;
                System.out.println("Retornando a URL="+res);
            } catch (ItemJaCadastradoException exc) {
                bean.setMensagemErro("Item ja cadastrado");
                System.out.println("item ja cadastrado");
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST, bean);
                request.setAttribute("drogas", drogas);
                request.setAttribute("doencas", doencas);
                res = URL_CADASTRO_MEDICAMENTO;
            } catch (PersistenceException exc) {
                res = URL_MEDICAMENTO_ERRO;
                throw new ServletException(exc);
            } catch (NullArgumentException exc) {
                res = URL_MEDICAMENTO_ERRO;
                throw new ServletException(exc);
            } catch (ItemNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (InvalidArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (SQLException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (NumberFormatException exc) {
                res = URL_CADASTRO_MEDICAMENTO;
                System.out.println("Retornando a URL="+res);
                bean.setMensagemErro(bean.getMensagemErro() + " Preço inválido");
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST,bean);
                request.setAttribute("drogas", drogas);
                request.setAttribute("doencas", doencas);
            }
            return res;
        }

    }// fim da class InsercaoMedicamentoHandler

    private class AlteracaoMedicamentoHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {

            String res = null, msg="";
            Medicamento oldMed = null, newMed = null;
            MedicamentoBean bean = new MedicamentoBean();
            List doencas = null, drogas = null;

            try {
            LoginUsuarioBean user = (LoginUsuarioBean) request.getSession(false).
                                    getAttribute("usuario");
            if(user!=null){
                if(user.getStatus() == sac.pessoa.UsuarioComum.STATUS_OPERADOR){
                    doencas = fachada.listarDoencas();
                    drogas = fachada.obtemDrogas();

                    bean = getMedicamentoBeanFromRequest(request, fachada);
                    bean.validaBean();
                    newMed = getMedicamentoFromBean(bean, fachada);
                    System.out.println("Criou o bean");
                    System.out.println("Validou o bean");
                    System.out.println("Procurando medicamento velho");
                    oldMed = fachada.procurarMedicamento(newMed.getId());
                    System.out.println("Achou medicamento velho: " + oldMed.getNome());
                    System.out.println("Alterando...");
                    fachada.alterarMedicamento(oldMed, newMed);
                    System.out.println("Alterou para: " + newMed.getNome());
                    res = URL_OPERACAO_OK;
                } else{
                    request.setAttribute(MEDICAMENTO_ERRO,
                          "Precisa ser Operador para realizar essa operacao!");
                    res = URL_MEDICAMENTO_ERRO;
                }
            } else{
                    request.setAttribute(MEDICAMENTO_ERRO,
                          "Você precisa estar logado!");
                    res = URL_MEDICAMENTO_ERRO;
            }
            } catch(CampoInvalidoException exc) {
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST, bean);
                request.setAttribute("doencas", doencas);
                request.setAttribute("drogas", drogas);
                res = URL_CADASTRO_MEDICAMENTO;
            } catch(NullArgumentException exc) {
                bean.setMensagemErro(exc.getMessage());
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST, bean);
                res = URL_CADASTRO_MEDICAMENTO;
            }catch (ItemNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, bean);
                res = URL_MEDICAMENTO_ERRO;
            }catch (ItemJaCadastradoException exc) {
                bean.setMensagemErro("Item ja cadastrado");
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST, bean);
                request.setAttribute("drogas", drogas);
                request.setAttribute("doencas", doencas);
                res = URL_CADASTRO_MEDICAMENTO;
            } catch (PersistenceException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (SQLException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            }catch (InvalidArgumentException exc) {
                bean.setMensagemErro(exc.getMessage());
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST, bean);
                request.setAttribute("drogas", drogas);
                request.setAttribute("doencas", doencas);
                res = URL_CADASTRO_MEDICAMENTO;
            } catch (NumberFormatException exc) {
                res = URL_CADASTRO_MEDICAMENTO;
                System.out.println("Retornando a URL="+res);
                bean.setMensagemErro(bean.getMensagemErro() + " Preço inválido");
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST,bean);
                request.setAttribute("drogas", drogas);
                request.setAttribute("doencas", doencas);
            }
            return res;
        }
    } // fim do AlteracaoMedicamentoHandler

    private class FillFormHandler extends SACHandler {

        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {
            MedicamentoBean medicamentoBean = new MedicamentoBean();
            Medicamento medicamento;
            String res;
            PessoaJuridicaBean PJBean = null;
            Object obj;
            int qtdSubmissoes = 0;
            boolean podeCadastrar = true;

            try{
                LoginUsuarioBean user = (LoginUsuarioBean) request.getSession(false).
                                        getAttribute("usuario");
                if(user!=null) {
                  if(user.getStatus() == sac.pessoa.UsuarioComum.STATUS_OPERADOR ||
                     user.getStatus() == sac.pessoa.UsuarioComum.STATUS_PESSOA_JURIDICA){

                    if(user.getStatus() == sac.pessoa.UsuarioComum.STATUS_PESSOA_JURIDICA){
                        obj = fachada.procuraUsuario(user.getLogin(), user.getStatus());
                        if (obj instanceof PessoaJuridica) {
                            System.out.println("é pessoa juridica!");
                            PJBean = new PessoaJuridicaBean();
                            PessoaJuridica pj = (PessoaJuridica) obj;
                            PJBean.setCnpj(pj.getCnpj());
                            PJBean.setNome(pj.getNome());
                            PJBean.setHomePage(pj.getHomePage());
                            qtdSubmissoes = fachada.getQtdMedicamentos(pj.getId());
                            podeCadastrar = qtdSubmissoes < QTD_MAX_SUBMISSOES_GRATIS? true : false;
                            System.out.println("PJ: "+ PJBean.getNome());
                        } else {
                            System.out.println("MedicamentoHandler.FillformHandler - objeto nao é PJ");
                            throw new PersistenceException("objeto nao é pessoa juridica");
                        } // fim do else de instanceof PessoaJuridica
                    } // fim do else de status == PessoaJuridica

                    String oid = request.getParameter(OID_INPUT);

                    if (oid == null) {
                        System.out.println("OID é null");
                        medicamentoBean = new MedicamentoBean();
                        medicamentoBean.setApresentacao(null);
                        medicamentoBean.setcontraIndicacoes("");
                        medicamentoBean.setDoencasRelacionadas(null);
                        medicamentoBean.setDrogaPrincipal(null);
                        medicamentoBean.setDrogasSecundarias(null);
                        medicamentoBean.setId("");
                        medicamentoBean.setIndicacoes("");
                        medicamentoBean.setLaboratorio(PJBean);
                        medicamentoBean.setMensagemErro("");
                        medicamentoBean.setNome("");
                        medicamentoBean.setPrecoAtacadoInferior("");
                        medicamentoBean.setPrecoAtacadoSuperior("");
                        medicamentoBean.setPrecoVarejo("");
                        medicamentoBean.setDoencas(fachada.listarDoencas());
                        medicamentoBean.setDrogas(fachada.obtemDrogas());
                    } else {
                        System.out.println("OID não é null");
                        podeCadastrar = true; // pois eh AlteracaoOperation
                        medicamento = fachada.procurarMedicamento(new OID(Long.parseLong(oid)));
                        medicamentoBean = getMedicamentoBean(medicamento, fachada);
                    }
                    if (podeCadastrar) {
                        List drogas = fachada.obtemDrogas(), doencas = fachada.listarDoencas();
  //                    List labs = fachada.procurarMedicamentoPeloNome("",0,10),
                        List apres = fachada.getApresentacoes();
                        request.setAttribute(MEDICAMENTO_BEAN_REQUEST, medicamentoBean);
                        request.setAttribute("drogas", drogas);
                        request.setAttribute("doencas", doencas);
                        request.setAttribute("apres", apres);
                        request.setAttribute("status", String.valueOf(user.getStatus()));

                        List pessoas = fachada.listarPessoasJuridicas();
        // <provisorio>
/*                        List pessoas = new Vector();
                        pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                        pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                        pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/        // <\provisorio>
                        request.setAttribute("labs", pessoas);
                        res = URL_CADASTRO_MEDICAMENTO;
                    } else {
                        request.setAttribute(MEDICAMENTO_ERRO,
                            "Usuario estorou limite de submissões gratuitas! Procurar administrador do sistema!");
                        res = URL_MEDICAMENTO_ERRO;
                    }
                } else{
                    request.setAttribute(MEDICAMENTO_ERRO,
                          "Precisa ser Operador para realizar essa operacao!");
                    res = URL_MEDICAMENTO_ERRO;
                }
            } else{
                    request.setAttribute(MEDICAMENTO_ERRO,
                          "Você precisa estar logado!");
                    res = URL_MEDICAMENTO_ERRO;
            }

            return res;
            } catch(PersistenceException pe){

            } catch(NullArgumentException nae){

            } catch(SQLException exc) {

            } catch(ItemNaoCadastradoException exc) {

            } catch(InvalidArgumentException exc) {

            }
            return URL_CADASTRO_MEDICAMENTO;
        }
    } // fim do FillFormHandler

    private class ObtemMedicamentoHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {

            String res = null;
            try {
                String oid = request.getParameter(OID_INPUT);
                Medicamento medicamento = fachada.procurarMedicamento(new OID(Long.parseLong(oid)));
                MedicamentoBean medicamentoBean = getMedicamentoBean(medicamento, fachada);
                request.setAttribute(MEDICAMENTO_BEAN_REQUEST, medicamentoBean);
                res = URL_OBTER_MEDICAMENTO;
                LoginUsuarioBean user = (LoginUsuarioBean) request.getSession(false).
                                        getAttribute("usuario");
                if (user != null) {
                    request.setAttribute("status", String.valueOf(user.getStatus()));
                    if ((UsuarioComum.STATUS_OPERADOR == user.getStatus()) ||
                        (user.getNome().equals(medicamentoBean.getLaboratorio().getNome()))) {
                          res = URL_CADASTRO_MEDICAMENTO;
                          List drogas = fachada.obtemDrogas(), doencas = fachada.listarDoencas();
      //                    List labs = fachada.procurarMedicamentoPeloNome("",0,10),
                          List apres = fachada.getApresentacoes();
                          request.setAttribute("drogas", drogas);
                          request.setAttribute("doencas", doencas);
                          request.setAttribute("apres", apres);
                          List pessoas = fachada.listarPessoasJuridicas();
      // <provisorio>
/*                      List pessoas = new Vector();
                      pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                      pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                      pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/      // <\provisorio>
                      request.setAttribute("labs", pessoas);
                    }
                }
            }catch (ItemNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch(NullArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (PersistenceException exc) {
                throw new ServletException(exc);
            } catch (SQLException exc){
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (InvalidArgumentException exc) {

            }
            return res;
        }
    }



    private class ConsultasMedicamentoHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {
            String res = "";
            try {
                request.setAttribute("doencas", fachada.listarDoencas());
                request.setAttribute("drogas", fachada.obtemDrogas());
                List pessoas = fachada.listarPessoasJuridicas();
// <provisorio>
/*                List pessoas = new Vector();
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/// <\provisorio>
                request.setAttribute("laboratorios", pessoas);
                res = URL_CONSULTA_MEDICAMENTO;
            } catch (PersistenceException exc) {
              //
            } catch(NullArgumentException exc) {

//            } catch (InvalidArgumentException exc) {

//            } catch (ItemNaoCadastradoException exc) {

            }
            return res;
        }
    }

    private class ConsultaMedicamentoNomeHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {
            String res = null;
            String posicao = "";
            String campo = "", valor = "";
            List medicamentos = null, beans = new LinkedList();
            MedicamentoBean bean = null;
            int posAtual = 0;

            try {

                campo = "Nome";
                valor = request.getParameter(campo);
                posicao = request.getParameter("posicaoAtual");
                posAtual = Integer.parseInt(posicao);
                System.out.println("Handler.ConsultaNome.Valor:" + valor);
                System.out.println("Handler.ConsultaNome.posAtual:" + posAtual);
                System.out.println("Handler.ConsultaNome.Valor:");
                medicamentos = fachada.procurarMedicamentoPeloNome(valor, posAtual, SIZE_RESP);
                if (medicamentos != null) {
                    for (int i=0; i<medicamentos.size();i++) {
                        beans.add(getMedicamentoBean((Medicamento) medicamentos.get(i), fachada));
                    }
                }
                System.out.println(campo + " - " + valor);
                request.setAttribute("medicamentos",beans);
                request.setAttribute("campo", campo);
                request.setAttribute("valor",valor);
                request.setAttribute("posicaoAtual", posicao);
                request.setAttribute("doencas", fachada.listarDoencas());
                request.setAttribute("drogas", fachada.obtemDrogas());

                List pessoas = fachada.listarPessoasJuridicas();
// <provisorio>
/*                List pessoas = new Vector();
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/// <\provisorio>
                request.setAttribute("laboratorios", pessoas);
                res = URL_CONSULTA_MEDICAMENTO;
            } catch (SQLException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (ItemNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (PersistenceException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (NullArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (InvalidArgumentException exc) {

            }
            return res;
        }

    }

    private class ConsultaMedicamentoDrogaHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {
            String res = null;
            String campo = "Droga", valor = "", posicao="";
            List medicamentos = null, beans = new LinkedList();
            MedicamentoBean bean = null;
            int posAtual = 0;

            try {
                valor = request.getParameter(campo);
                posicao = request.getParameter("posicaoAtual");
                posAtual = Integer.parseInt(posicao);
                Droga droga = fachada.procurarDroga(new OID(Long.parseLong(valor)));
                medicamentos = fachada.procurarMedicamentoPelaDroga(droga, posAtual, SIZE_RESP);
                if (medicamentos != null) {
                    for (int i=0; i<medicamentos.size();i++) {
                        beans.add(getMedicamentoBean((Medicamento) medicamentos.get(i), fachada));
                    }
                }
                request.setAttribute("medicamentos", beans);
                request.setAttribute("campo", campo);
                request.setAttribute("valor",droga.getID().getLongValue() + "");
                request.setAttribute("posicaoAtual", posicao);
                request.setAttribute("doencas", fachada.listarDoencas());
                request.setAttribute("drogas", fachada.obtemDrogas());

                List pessoas = fachada.listarPessoasJuridicas();
// <provisorio>
/*                List pessoas = new Vector();
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/// <\provisorio>
                request.setAttribute("laboratorios", pessoas);
                res = URL_CONSULTA_MEDICAMENTO;
            } catch (SQLException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (ItemNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (PersistenceException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (NullArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
/*            } catch (DrogaNaoCadastradaException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
*/            } catch (InvalidArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            }
            return res;
        }

    }

    private class ConsultaMedicamentoDoencaHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {
            String res = null;
            String posicao = "", campo = "Doenca", valor = "";
            List medicamentos = null, beans = new LinkedList();
            MedicamentoBean bean = null;
            int posAtual = 0;

            try {
                valor = request.getParameter(campo);
                posicao = request.getParameter("posicaoAtual");
                posAtual = Integer.parseInt(posicao);

                Doenca doenca = fachada.procurarDoenca(valor);
                medicamentos = fachada.procurarMedicamentoPelaDoenca(doenca, posAtual, SIZE_RESP);
                if (medicamentos != null) {
                    for (int i=0; i<medicamentos.size();i++) {
                        if (medicamentos.get(i) != null) {
                            beans.add(getMedicamentoBean((Medicamento) medicamentos.get(i), fachada));
                        }
                    }
                }
                System.out.println(campo + " - " + valor);
                request.setAttribute("medicamentos",beans);
                request.setAttribute("campo", campo);
                request.setAttribute("valor",doenca.getNome());
                request.setAttribute("posicaoAtual", posicao);
                request.setAttribute("doencas", fachada.listarDoencas());
                request.setAttribute("drogas", fachada.obtemDrogas());

                List pessoas = fachada.listarPessoasJuridicas();
// <provisorio>
/*                List pessoas = new Vector();
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/// <\provisorio>
                request.setAttribute("laboratorios", pessoas);
                res = URL_CONSULTA_MEDICAMENTO;
            } catch (SQLException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (MedicamentoNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (PersistenceException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (NullArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (DoencaNaoCadastradaException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (InvalidArgumentException exc) {

            } catch (ItemNaoCadastradoException exc) {

            }
            return res;
        }

    }

    private class ConsultaMedicamentoLaboratorioHandler extends SACHandler {
        public String processRequest(HttpServletRequest request, HttpServletResponse response,
                 SACFachada fachada) throws ServletException, IOException {
            String res = null;
            String campo = "Laboratorio", valor = "", posicao = "";
            List medicamentos = null, beans = new LinkedList();
            MedicamentoBean bean = null;
            int posAtual = 0;

            try {
                campo = "Laboratorio";
                valor = request.getParameter(campo);
                posicao = request.getParameter("posicaoAtual");
                posAtual = Integer.parseInt(posicao);
                PessoaJuridica laboratorio = (PessoaJuridica) fachada.procuraUsuario(valor, UsuarioComum.STATUS_PESSOA_JURIDICA);
                medicamentos = fachada.procurarMedicamentoPeloLaboratorio(laboratorio, posAtual, SIZE_RESP);
                if (medicamentos != null) {
                    for (int i=0; i<medicamentos.size();i++) {
                        beans.add(getMedicamentoBean((Medicamento) medicamentos.get(i), fachada));
                    }
                }
                System.out.println(campo + " - " + valor);
                request.setAttribute("medicamentos", beans);
                request.setAttribute("campo", campo);
                request.setAttribute("valor",valor);
                request.setAttribute("posicaoAtual",posicao);
                request.setAttribute("doencas", fachada.listarDoencas());
                request.setAttribute("drogas", fachada.obtemDrogas());

                List pessoas = fachada.listarPessoasJuridicas();
// <provisorio>
/*                List pessoas = new Vector();
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901234"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678901239"));
                pessoas.add((PessoaJuridica) fachada.procurarPessoaJuridica("12345678904567"));
*/// <\provisorio>
                request.setAttribute("laboratorios", pessoas);
                res = URL_CONSULTA_MEDICAMENTO;
            } catch (SQLException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (ItemNaoCadastradoException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (PersistenceException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (NullArgumentException exc) {
                request.setAttribute(MEDICAMENTO_ERRO, exc.getMessage());
                res = URL_MEDICAMENTO_ERRO;
            } catch (InvalidArgumentException exc) {

            }
            return res;
        }

    }

    public MedicamentoBean getMedicamentoBeanFromRequest(HttpServletRequest request, SACFachada fachada)
    throws NullArgumentException, DrogaNaoCadastradaException, PersistenceException, DoencaNaoCadastradaException,
    InvalidArgumentException, ItemNaoCadastradoException{
        String precoVarejo, precoAtacInf, precoAtacSup;
        String [] apres = request.getParameterValues(APRESENTACAO_INPUT);
        apres = (apres!= null)? apres : new String[0];
        MedicamentoBean medicamentoBean = new MedicamentoBean();
        medicamentoBean.setNome(request.getParameter(NOME_INPUT));
        medicamentoBean.setApresentacao(getApresentacao(apres));//getApresentacao(request.getParameter(APRESENTACAO_INPUT)));

          PessoaJuridica pj = fachada.procurarPessoaJuridica(request.getParameter(LABORATORIO_INPUT));
          PessoaJuridicaBean pjB = new PessoaJuridicaBean();
          pjB.setCnpj(pj.getCnpj());
          pjB.setHomePage(pj.getHomePage());
          pjB.setNome(pj.getNome());

        medicamentoBean.setLaboratorio(pjB);
        medicamentoBean.setIndicacoes(request.getParameter(INDICACOES_INPUT));
        medicamentoBean.setcontraIndicacoes(request.getParameter(CONTRA_INDICACOES_INPUT));
        medicamentoBean.setDrogaPrincipal(new DrogaBean(fachada.procurarDroga(new OID(Long.parseLong(request.getParameter(DROGA_PRINCIPAL_INPUT))))));
        medicamentoBean.setDrogasSecundarias(getDrogas(request.getParameterValues(DROGAS_SECUNDARIAS_INPUT), fachada));
        medicamentoBean.setDoencasRelacionadas(getDoencas(request.getParameterValues(DOENCAS_RELACIONADAS_INPUT), fachada));
        medicamentoBean.setPrecoVarejo(request.getParameter(PRECO_VAREJO_INPUT));
        medicamentoBean.setPrecoAtacadoInferior(request.getParameter(PRECO_ATACADO_INFERIOR_INPUT));
        medicamentoBean.setPrecoAtacadoSuperior(request.getParameter(PRECO_ATACADO_SUPERIOR_INPUT));
        medicamentoBean.setId(request.getParameter(OID_INPUT));
        return medicamentoBean;
    }

    public Medicamento getMedicamentoFromBean(MedicamentoBean medicamentoBean, SACFachada fachada)
    throws NullArgumentException, DrogaNaoCadastradaException, PersistenceException, DoencaNaoCadastradaException,
    ItemNaoCadastradoException, InvalidArgumentException, NumberFormatException{
        String precoVarejo, precoAtacInf, precoAtacSup;
        Medicamento medicamento = new Medicamento();
        medicamento.setNome(medicamentoBean.getNome());
        medicamento.setApresentacao(medicamentoBean.getApresentacao());
// alterado em 12/03
        medicamento.setLaboratorio(fachada.procurarPessoaJuridica(medicamentoBean.getLaboratorio().getCnpj()));
        medicamento.setIndicacoes(medicamentoBean.getIndicacoes());
        medicamento.setcontraIndicacoes(medicamentoBean.getcontraIndicacoes());
        medicamento.setDrogaPrincipal(medicamentoBean.getDrogaPrincipal().getDroga());
        medicamento.setDrogasSecundarias(getDrogasFromBean(medicamentoBean.getDrogasSecundarias(), fachada));
        medicamento.setDoencasRelacionadas(getDoencasRelFromBean(medicamentoBean.getDoencasRelacionadas(), fachada));

        precoVarejo = medicamentoBean.getPrecoVarejo();
        precoAtacInf = medicamentoBean.getPrecoAtacadoInferior();
        precoAtacSup = medicamentoBean.getPrecoAtacadoSuperior();
        try {
        if (!precoVarejo.equals("")) {
            precoVarejo = precoVarejo.replace(',','.');
            medicamento.setPrecoVarejo(Double.parseDouble(precoVarejo));
        }
        if (!precoAtacInf.equals("")) {
            precoAtacInf = precoAtacInf.replace(',','.');
            medicamento.setPrecoAtacadoInferior(Double.parseDouble(precoAtacInf));
        }
        if (!precoAtacSup.equals("")) {
            precoAtacSup = precoAtacSup.replace(',','.');
            medicamento.setPrecoAtacadoSuperior(Double.parseDouble(precoAtacSup));
        }
        } catch (NumberFormatException exc) {
            throw new NumberFormatException();
        }
        String oid = medicamentoBean.getId();
        if (oid != null) {
            medicamento.setId(new OID (Long.parseLong(oid)));
        }
        return medicamento;
    }

    public MedicamentoBean getMedicamentoBean(Medicamento medicamento, SACFachada fachada)
    throws PersistenceException, NullArgumentException{
        MedicamentoBean medicamentoBean = new MedicamentoBean();
        medicamentoBean.setApresentacao(medicamento.getApresentacao());
        medicamentoBean.setcontraIndicacoes(medicamento.getcontraIndicacoes());
        medicamentoBean.setDoencasRelacionadas(medicamento.getDoencasRelacionadas());
        medicamentoBean.setDrogaPrincipal(new DrogaBean(medicamento.getDrogaPrincipal()));
        medicamentoBean.setDrogasSecundarias(medicamento.getDrogasSecundarias());
        if (medicamento.getId() != null) {
            medicamentoBean.setId(medicamento.getId().getLongValue() + "");
        }
        medicamentoBean.setIndicacoes(medicamento.getIndicacoes());
          PessoaJuridica pj = medicamento.getLaboratorio();
          PessoaJuridicaBean pjB = new PessoaJuridicaBean();
          pjB.setCnpj(pj.getCnpj());
          pjB.setHomePage(pj.getHomePage());
          pjB.setNome(pj.getNome());
        medicamentoBean.setLaboratorio(pjB);
        medicamentoBean.setMensagemErro("");
        medicamentoBean.setNome(medicamento.getNome());
        medicamentoBean.setPrecoAtacadoInferior(medicamento.getPrecoAtacadoInferior()+"");
        medicamentoBean.setPrecoAtacadoSuperior(medicamento.getPrecoAtacadoSuperior()+"");
        medicamentoBean.setPrecoVarejo(medicamento.getPrecoVarejo()+"");
        medicamentoBean.setDoencas(fachada.listarDoencas());
        medicamentoBean.setDrogas(fachada.obtemDrogas());
        return medicamentoBean;
    }

    public List getApresentacao(String[] apres) throws NullArgumentException{
            List resp = new Vector();
            Apresentacao apresObj = null;
            for (int i=0; i< apres.length; i++) {
                apresObj = new Apresentacao();
                apresObj.setNome(apres[i]);
                System.out.println("Apresentacao: " + apresObj.getNome());
                resp.add(apresObj);
            }
            return resp;
        }

/*      public List getLaboratorios(String labs) throws NullArgumentException{
            List resp = null;
        	  Laboratorio labObj = null;
            if (!labs.equals("")) {
                resp = new Vector();
                StringTokenizer str = new StringTokenizer(labs, "\n");
                System.out.println("Pegando " + str.countTokens() + " laboratorios ...");
                while (str.hasMoreElements()) {
                    labObj = new Laboratorio();
                    labObj.setNome((String) str.nextElement());
                    System.out.println("Laboratorio: " + labObj.getNome());
                    resp.add(labObj);
                }
            }
            return resp;
        }
*/
        public List getDrogasBean(List drogas, SACFachada fachada) throws NullArgumentException,
        DrogaNaoCadastradaException, PersistenceException, ItemNaoCadastradoException,
        InvalidArgumentException{
            List resp = null;
            Droga droga = null;
            if (drogas != null) {
              System.out.println("Pegando "+drogas.size()+" drogas ...");
                for (int i = 0; i < drogas.size(); i++) {
                    droga = ((DrogaBean) drogas.get(i)).getDroga();
                    System.out.println("Droga: " + droga.getNome());
                    resp.add(droga);
                }
            }
            return resp;
        }

        private List getDrogasFromBean (List drogasSecBean, SACFachada fachada) throws NullArgumentException{
            List resp = null;

            if (drogasSecBean != null) {
                resp = new Vector();
                for (int i=0; i< drogasSecBean.size();i++) {
                    resp.add(((DrogaBean)drogasSecBean.get(i)).getDroga());
                }
            }
            return resp;
        }

        private List getDoencasRelFromBean (List doencasBean, SACFachada fachada)
        throws NullArgumentException{
            List resp = null;

            if (doencasBean != null) {
                resp = new Vector();
                for (int i=0; i<  doencasBean.size();i++) {
                    resp.add(((DoencaBean)doencasBean.get(i)).getDoenca());
                }
            }
            return resp;
        }

        private List getDrogas(String[] drogas, SACFachada fachada)  throws NullArgumentException,
        PersistenceException, ItemNaoCadastradoException, InvalidArgumentException{
            List resp = null;
            Droga droga = null;
            if (drogas != null) {
                resp = new Vector();
                System.out.println("Pegando "+drogas.length+" drogas ...");
                for (int i = 0; i < drogas.length; i++) {
                    droga = fachada.procurarDroga(new OID(Long.parseLong(drogas[i])));
                    System.out.println("Droga: " + droga.getNome());
                    resp.add(droga);
                }
            }
            return resp;
        }

        private List getDoencas(String[] doencas, SACFachada fachada)  throws NullArgumentException,
        PersistenceException, ItemNaoCadastradoException{
            List resp = null;
            Doenca doenca = null;
            if (doencas != null) {
                resp = new Vector();
                System.out.println("Pegando "+doencas.length+" doencas ...");
                for (int i = 0; i < doencas.length; i++) {
                    doenca = fachada.procurarDoenca(new OID(Long.parseLong(doencas[i])));
                    System.out.println("Doenca: " + doenca.getNome());
                    resp.add(doenca);
                }
            }
            return resp;
        }

}
