/*
 * ListaPlanos.java
 *
 * Created on Aug 29, 2008, 2:57:16 PM
 */
 
package planosactuacao;

import com.sun.data.provider.RowKey;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.Table;
import com.sun.webui.jsf.component.TableRowGroup;
import db.entidades.PlanoActuacao;
import db.providers.UtilizadoresDataProvider;
import db.entidades.Utilizador;
import db.providers.PlanosDataProvider;
import global.Global;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import siprp.database.cayenne.providers.PlanoActuacaoDAO;
import siprp.planoactuacao.print.PlanoActuacaoPDFCreator;
import tabledataproviders.PlanosActualDataProvider;
import tabledataproviders.PlanosConcluidosDataProvider;
import tabledataproviders.PlanosSeguimentoDataProvider;
import utils.JSFUtils;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @author lluis
 */
public class ListaPlanos extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private Table table1 = new Table();

    public Table getTable1() {
        return table1;
    }

    public void setTable1(Table t) {
        this.table1 = t;
    }
    private TableRowGroup tableRowGroup1 = new TableRowGroup();

    public TableRowGroup getTableRowGroup1() {
        return tableRowGroup1;
    }

    public void setTableRowGroup1(TableRowGroup trg) {
        this.tableRowGroup1 = trg;
    }
    private TableRowGroup tableRowGroup2 = new TableRowGroup();

    public TableRowGroup getTableRowGroup2() {
        return tableRowGroup2;
    }

    public void setTableRowGroup2(TableRowGroup trg) {
        this.tableRowGroup2 = trg;
    }
    private TableRowGroup tableRowGroup3 = new TableRowGroup();

    public TableRowGroup getTableRowGroup3() {
        return tableRowGroup3;
    }

    public void setTableRowGroup3(TableRowGroup trg) {
        this.tableRowGroup3 = trg;
    }

    // </editor-fold>
     PlanosDataProvider pdp = new PlanosDataProvider();
    private HtmlPanelGrid gridActual = new HtmlPanelGrid();

    public HtmlPanelGrid getGridActual() {
        return gridActual;
    }

    public void setGridActual(HtmlPanelGrid hpg) {
        this.gridActual = hpg;
    }

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public ListaPlanos() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("ListaPlanos Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
        //UIComponent emptyCol = tableRowGroup1.getEmptyDataText();
        System.out.println("LISTA PLANOS - PRERENDER");        
        
        FacesContext fc = getFacesContext();
        String user_id = JSFUtils.getRequestParameter(fc, "user");
        System.out.println("LISTA PLANOS - USER ID : " + user_id);
        Utilizador u = null;
        if(user_id != null)
        {
            
            try
            {
                Integer userId = new Integer(Integer.parseInt(user_id));

                try
                {
                    UtilizadoresDataProvider udp = new UtilizadoresDataProvider();
                    udp.checkConnection();
                    u = udp.getUtilizador(userId);
                    getSessionBean1().setCurrentUser(u);


                }
                catch(Exception ex1)
                {
                    ex1.printStackTrace();
                }
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }            
            
        }

        u = getSessionBean1().getCurrentUser();
        if(u.getTipo().intValue() == Global.DIRECTOR_SIPRP)
        {
            gridActual.setRendered(false);
            tableRowGroup2.setEmptyDataMsg("Sem registos");
            tableRowGroup3.setEmptyDataMsg("Sem registos");        
        }

        if(u.getTipo().intValue() != Global.DIRECTOR_SIPRP)
        {
            getSessionBean1().setDisableMenuUtilizadores(true);
            tableRowGroup1.setEmptyDataMsg("Sem registos");
            tableRowGroup2.setEmptyDataMsg("Sem registos");
            tableRowGroup3.setEmptyDataMsg("Sem registos");        
        }        

        initialize();                        

    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public String hyperlink1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "editar_plano";
    }

    public String goEditarPlano_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        PlanoActuacao p = getTableActivosRowData();
        getSessionBean1().setPlanoActuacao(p); 
        
        
        //showPlano(p);
        //dummy 
        //getSessionBean1().setFase(2);
        return "editar_plano";
    }
    
    public String goVerPlanoFromSeguimento_action(){
        PlanoActuacao p = getTableSeguimentoRowData();
        getSessionBean1().setPlanoActuacao(p);         
        return "ver_plano";        
    }
    
    public String goVerPlanoFromConcluidos_action(){
        PlanoActuacao p = getTableConcluidosRowData();
        getSessionBean1().setPlanoActuacao(p);         
        return "ver_plano";        
    }    

    public String goImprimirPlano_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        PlanoActuacao p = getTableActivosRowData();
        PlanoActuacaoPDFCreator pdfCreator = new PlanoActuacaoPDFCreator();
        try
        {
            byte[] pdf = pdfCreator.createPDF(p.getId()); 
            showPdf(pdf);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        return null;
    }
    
    public String goImprimirPlanoFromSeguimento_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        PlanoActuacao p = getTableSeguimentoRowData();
        PlanoActuacaoPDFCreator pdfCreator = new PlanoActuacaoPDFCreator();
        try
        {
            byte[] pdf = pdfCreator.createPDF(p.getId()); 
            showPdf(pdf);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

        return null;
    }    
    
    public String goImprimirPlanoFromConcluidos_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        PlanoActuacao p = getTableConcluidosRowData();  
        PlanoActuacaoPDFCreator pdfCreator = new PlanoActuacaoPDFCreator();
        try
        {
            byte[] pdf = pdfCreator.createPDF(p.getId()); 
            showPdf(pdf);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        

        return null;
    } 
    
    private void showPdf(byte[] pdf) throws Exception
    {
//        FacesContext fc = getFacesContext();
//        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
//        response.setContentType("application/pdf");
//        //response.getOutputStream().flush();
//        response.flushBuffer();             
//        response.getOutputStream().write(pdf, 0, pdf.length);
//        fc.getResponseComplete();
        
        System.out.println("PDF LEN : " + pdf.length);
        
FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response =
(HttpServletResponse)context.getExternalContext().getResponse();
        
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
//response.setHeader("Content-disposition","inline; filename=kiran.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType( "application/pdf" );
//response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\"");
        response.addHeader("Content-disposition", "attachment;filename=\"Plano.pdf\"");        
        
        //response.setHeader("Content-disposition", "filename=plano.pdf");
        response.setContentLength(pdf.length);                
        //try {
                response.getOutputStream().write(pdf);
                response.getOutputStream().flush();
                response.getOutputStream().close();
                context.responseComplete();
//        } catch (IOException e) {
//                e.printStackTrace();
//        }        
    System.out.println("SHOW PDF");
   }
    
    
    private void initialize()
    {
        Utilizador u = getSessionBean1().getCurrentUser();
        
        Integer estabelecimento_id = null;
        if(u.getTipo().intValue() != Global.TECNICO_HS)
        {
            estabelecimento_id = u.getEstabelecimento_id();
        }
        PlanoActuacaoDAO pa = new PlanoActuacaoDAO();
        
        List<Date> list = new ArrayList();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 27);
        calendar.set(Calendar.MONTH, 9);
        calendar.set(Calendar.YEAR, 2008);        
        java.util.Date date = new java.util.Date(calendar.getTimeInMillis()); 
        
//        list.add(date);
//        List<HsRelatorio> listPlanos = pa.getRelatoriosNotIn(list);
//        System.out.println("PLANOS = " + listPlanos.size());
//        Iterator iter = listPlanos.iterator();
//        while(iter.hasNext())
//        {
//            HsRelatorio relatorio = (HsRelatorio) iter.next();
//
//            List<HsRelatorioRisco> relatorio_riscoList = relatorio.getHsRelatorioRiscoArray();
//            HsRelatorioRisco rr = null;
//            HsRelatorioMedida rm = null;
//
//            
//            //next is to get estabelecimento from relatorio
//            
////            MarcacoesEstabelecimento me = relatorio.getToHsMarcacoesEstabelecimento();
////            Estabelecimentos es = me.getToEstabelecimentos();
////            Integer id = es.getId(); // estabelecimento id ??
//        }
        
        PlanosActuacao planos = new PlanosActuacao(u);
        
        List listPlanosActivos = planos.getPlanosActivos(u);
        getSessionBean1().getPlanosActualDataProvider().setList(listPlanosActivos);
        
        List listPlanosSeguimento = planos.getPlanosSeguimento(u);
        getSessionBean1().getPlanosSeguimentoDataProvider().setList(listPlanosSeguimento);        
        
        List listPlanosConcluidos = planos.getPlanosConcluidos(u);
        getSessionBean1().getPlanosConcluidosDataProvider().setList(listPlanosConcluidos);                
        
        //checkPlanosDelayed();
    }
    
    

    
    private PlanoActuacao getTableActivosRowData()
    {
        RowKey rk = tableRowGroup1.getRowKey();
        int k = Integer.parseInt(rk.getRowId());        
        PlanosActualDataProvider provider = (PlanosActualDataProvider) tableRowGroup1.getSourceData();
        ArrayList list = (ArrayList) provider.getList();
        PlanoActuacao p = (PlanoActuacao)list.get(k);
        return p;
    } 
    
    private PlanoActuacao getTableSeguimentoRowData()
    {
        RowKey rk = tableRowGroup2.getRowKey();
        int k = Integer.parseInt(rk.getRowId());        
        PlanosSeguimentoDataProvider provider = (PlanosSeguimentoDataProvider) tableRowGroup2.getSourceData();
        ArrayList list = (ArrayList) provider.getList();
        PlanoActuacao p = (PlanoActuacao)list.get(k);

        return p;
    } 
    
    private PlanoActuacao getTableConcluidosRowData()
    {
        RowKey rk = tableRowGroup3.getRowKey();
        int k = Integer.parseInt(rk.getRowId());        
        PlanosConcluidosDataProvider provider = (PlanosConcluidosDataProvider) tableRowGroup3.getSourceData();
        ArrayList list = (ArrayList) provider.getList();
        PlanoActuacao p = (PlanoActuacao)list.get(k);
        return p;
    } 
    
    private void checkPlanosDelayed()
    {
        
    }
    
    
    
//    private void showPlano(PlanoActuacao p)
//    {
//        System.out.println("PLANO : " + p.getData_visita_str() + " | "  + p.getFase_nome()  + " | " + p.getNome_estabelecimento());        
//        System.out.println("=================================================================");
//        showAreas(p.getAreas());
//        System.out.println("=================================================================");        
//    }
//    
//    private void showAreas(List<Area> areas)
//    {
//        for(Area a : areas)
//        {
//            System.out.println("   " + a.getDescricao());
//            showRiscos(a.getRiscos());
//        }
//    }
//    
//    private void showRiscos(List<Risco> riscos)
//    {
//        for(Risco r : riscos)
//        {
//            System.out.println("      " + r.getDescricao());
//            showValores(r.getValores());
//        }        
//    }
//    
//    private void showValores(List<Valor> valores)
//    {
//        for(Valor v : valores)
//        {
//            System.out.println("         " + v.getValor());
//            showMedidas(v.getMedidas());
//        }                
//    }
//    
//    private void showMedidas(List<Medida> medidas)
//    {
//        for(Medida m : medidas)
//        {
//            System.out.println("            " + m.getDescricao());
//            showPostos(m.getPostos());
//        }                        
//    }
//    
//    private void showPostos(List<PostoTrabalho> postos)
//    {
//        for(PostoTrabalho p : postos)
//        {
//            System.out.println("               " + p.getDescricao());
//        }                                
//    }    
    
}

