/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.dgfip.xemelios.web.gwt.client.widget.exports;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.ConfigExportDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.DocumentDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.DocumentsDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.EtatDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.SearchSessionDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.service.ServiceLocator;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.utils.GWTUtils;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author chm
 */
public class DlgSelectExport extends DialogBox {
    private static final int MODE_CONFIG = 1;
    private static final int MODE_EXECUTE = 2;
    private ListBox cbxDocs = null;
    private ListBox cbxEtats = null;
    private Button pbSearch = null, pbExecute = null, pbEdit = null, pbDelete = null, pbNew = null, pbClose = null;
    private FlexTable table = null;
    private DocumentsDTO docs;
    private ArrayList<String> configsId = null;
    private int selectedRow = -1;
    private String currentDocId=null, currentEtatId=null,selectedConfigId=null;
    private int __mode=0;
    private String searchSessionId = null;
    private boolean searchSessionInitialized=false;
    private boolean documentsInitialized=false;
    private SearchSessionDTO searchSession=null;


    public DlgSelectExport() {
        super(false,true);
        setText("Liste des configurations d'export");
        __mode = MODE_CONFIG;
        initComponents();
    }

    public DlgSelectExport(String searchSessionId) {
        super(false,true);
        this.searchSessionId=searchSessionId;
        setText("Liste des configurations d'export");
        __mode = MODE_EXECUTE;
        initComponents();
        initSession();
    }

    protected void initComponents() {
        VerticalPanel vPane = new VerticalPanel();
        DecoratorPanel p1 = new DecoratorPanel();
        Grid grd = new Grid(2,3);
        grd.setText(0,0,"Document");
        grd.setText(1,0,"Etat");
        cbxDocs = new ListBox(false);
        cbxDocs.setVisibleItemCount(1);
        grd.setWidget(0,1,cbxDocs);
        cbxEtats = new ListBox(false);
        cbxEtats.setVisibleItemCount(1);
        grd.setWidget(1,1, cbxEtats);
        pbSearch = new Button("Rechercher");
        pbSearch.setEnabled(false);
        grd.setWidget(1, 2, pbSearch);
        p1.add(grd);

        vPane.add(p1);

        table = new FlexTable();
//        table.setWidth("100%");
        table.addStyleName("TblListExport");
        table.setWidget(0,0,new HTMLHeader("Code"));
        table.setWidget(0,1,new HTMLHeader("Libell&eacute;"));
        table.setWidget(0,2,new HTMLHeader("Cr&eacute;ateur"));
        table.setWidget(0,3,new HTMLHeader("Date cr&eacute;ation"));

        ScrollPanel sc = new ScrollPanel(table);
        sc.setHeight("100px");
        vPane.add(sc);

        HorizontalPanel buttonPane = new HorizontalPanel();
        pbExecute = new Button("Executer");
        pbExecute.setEnabled(false);
        pbDelete = new Button("Supprimer");
        pbDelete.setEnabled(false);
        pbEdit = new Button("Modifier");
        pbEdit.setEnabled(false);
        pbNew = new Button("Nouveau");
        pbNew.setEnabled(false);
        pbClose = new Button("Fermer");
        pbClose.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                hide(true);
            }
        });
        buttonPane.add(pbClose);
        buttonPane.add(pbExecute);
        buttonPane.add(pbDelete);
        buttonPane.add(pbEdit);
        buttonPane.add(pbNew);
        vPane.add(buttonPane);

        setWidget(vPane);

        initListeners();


        center();

        ServiceLocator.getXemeliosService().getDocuments(new AsyncCallback() {
            public void onFailure(Throwable caught) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }
            public void onSuccess(Object result) {
                initDocuments((DocumentsDTO)result);
            }
        });
    }
    protected void initSession() {
        ServiceLocator.getXemeliosService().getSearchSessionInformations(searchSessionId, new AsyncCallback<SearchSessionDTO>() {
            public void onFailure(Throwable caught) {
                GWTUtils.handleRPCError(caught);
            }
            public void onSuccess(SearchSessionDTO result) {
                setSearchSessionInformations(result);
                if(docs!=null) initDocuments(docs);
            }
        });
    }
    private void setSearchSessionInformations(SearchSessionDTO infos) {
        this.searchSession=infos;
        searchSessionInitialized=true;
    }
    private void initDocuments(DocumentsDTO docs) {
        this.docs=docs;
        cbxDocs.clear();
        if(getMode()==MODE_CONFIG) {
            cbxDocs.addItem(new HTML("S&eacute;lectionnez un document").getHTML(),"");
            for(DocumentDTO doc:docs.getDocuments()) {
                cbxDocs.addItem(doc.getLibelle(), doc.getId());
            }
        } else {
            if(searchSessionInitialized) {
                for(DocumentDTO doc:docs.getDocuments()) {
                    if(doc.getId().equals(searchSession.getDocumentId())) {
                        cbxDocs.addItem(doc.getLibelle(), doc.getId());
                        cbxDocs.setSelectedIndex(0);
                        currentDocId = cbxDocs.getValue(cbxDocs.getSelectedIndex());
                        cbxEtats.clear();
                        for(EtatDTO etat:doc.getEtats()) {
                            if(etat.getId().equals(searchSession.getEtatId())) {
                                cbxEtats.addItem(etat.getLibelle(), etat.getId());
                            }
                        }
                        cbxEtats.setSelectedIndex(0);
                        currentEtatId = cbxEtats.getValue(cbxEtats.getSelectedIndex());
                        pbSearch.setEnabled(true);
                        pbNew.setEnabled(true);
                    }
                }
                cbxDocs.setEnabled(false);
                cbxEtats.setEnabled(false);
            }
        }
    }

    protected void initListeners() {
        cbxDocs.addChangeListener(new ChangeListener() {
            public void onChange(Widget sender) {
                if(cbxDocs.getSelectedIndex()>0) {
                    String value = cbxDocs.getValue(cbxDocs.getSelectedIndex());
                    currentDocId = value;
                    if(value!=null && value.length()>0) {
                        cbxEtats.setEnabled(true);
                        // reload etats from this doc
                        cbxEtats.clear();
                        cbxEtats.addItem(new HTML("S&eacute;lectionnez un &eacute;tat").getHTML(),"");
                        for(DocumentDTO doc:docs.getDocuments()) {
                            if(doc.getId().equals(value)) {
                                for(EtatDTO etat:doc.getEtats()) {
                                    cbxEtats.addItem(etat.getLibelle(), etat.getId());
                                }
                            }
                        }
                    } else {
                        cbxEtats.setEnabled(false);
                        currentDocId=null;
                        currentEtatId=null;
                        selectedConfigId=null;
                    }
                }
            }
        });

        cbxEtats.addChangeListener(new ChangeListener() {
            public void onChange(Widget sender) {
                String value = cbxEtats.getValue(cbxEtats.getSelectedIndex());
                pbSearch.setEnabled(value!=null && value.length()>0);
                pbNew.setEnabled(value!=null && value.length()>0);
                if(value!=null && value.length()>0) {
                    currentEtatId=value;
                } else {
                    currentEtatId=null;
                    selectedConfigId=null;
                }
            }
        });

        pbSearch.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                ServiceLocator.getXemeliosService().getListeConfigExport(
                        currentDocId,
                        currentEtatId,
                        new AsyncCallback() {
                    public void onFailure(Throwable caught) {
                        GWTUtils.handleRPCError(caught);
                    }
                    public void onSuccess(Object result) {
                        while(table.getRowCount()>1) table.removeRow(1);
                        @SuppressWarnings("unchecked")
                        List<ConfigExportDTO> configs = (List<ConfigExportDTO>)result;
                        configsId = new ArrayList<String>();
                        for(ConfigExportDTO cfg:configs) {
                            int newRow = table.getRowCount();
                            table.setText(newRow, 0, cfg.getCode());
                            table.setText(newRow,1,cfg.getLibelle());
                            table.setText(newRow,2,cfg.getOwner());
                            table.setText(newRow,3,cfg.getDateCreation());
                            configsId.add(cfg.getId());
                        }
                    }
                });
            }
        });

        table.addTableListener(new TableListener() {
            public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
                if(row==0) return;
                if(selectedRow>=0) {
                    table.getRowFormatter().removeStyleName(selectedRow+1, "highlited");
                }
                if((selectedRow-1)==row) {
                    // unselect row
                    selectedRow = -1;
                    selectedConfigId=null;
                } else {
                    selectedRow = row-1;
                    table.getRowFormatter().addStyleName(row, "highlited");
                    selectedConfigId = configsId.get(selectedRow);
                }
                enableButtons();
            }
        });

        pbDelete.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                if(Window.confirm(new HTML("Etes-vous certain de vouloir supprimer ce mod&egrave;le d'export ?").getHTML())) {
                    ServiceLocator.getXemeliosService().deleteExportModel(currentDocId, currentEtatId, selectedConfigId, new AsyncCallback() {
                        public void onFailure(Throwable caught) {
                            Window.alert(caught.getMessage());
                        }
                        public void onSuccess(Object result) {
                            String ret = (String)result;
                            if("OK".equals(ret)) {
                                pbSearch.click();
                            } else {
                                Window.alert(ret);
                            }
                        }
                    });
                }
            }
        });
        pbEdit.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                DlgEditConfig dec = new DlgEditConfig(currentDocId,currentEtatId,selectedConfigId);
                dec.show();
                pbSearch.click();
            }
        });
        pbNew.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                //createNewModel(currentDocId,currentEtatId);
                DlgEditConfig dec = new DlgEditConfig(currentDocId,currentEtatId);
                dec.show();
                pbSearch.click();
            }
        });
        pbExecute.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                DlgGetExportDetails dlg = new DlgGetExportDetails(DlgSelectExport.this);
                dlg.show();
            }
        });
    }
    protected void runExport(String fileName, String exportName) {
        ServiceLocator.getXemeliosService().createExportRequest(searchSessionId, selectedConfigId, fileName, exportName, new AsyncCallback<String>() {
            public void onFailure(Throwable caught) {
                GWTUtils.handleRPCError(caught);
            }
            public void onSuccess(String result) {
                String s = "Votre demande d'export a bien &eacute;t&eacute; enregistr&eacute;e.\n" +
                        "Vous pouvez consulter l'avancement de l'export en allant dans\nle menu Exports / Mes exports...";
                Window.alert(new HTML(s).getHTML());
            }
        });
    }

    private void enableButtons() {
        boolean enable = selectedRow>=0;

        pbDelete.setEnabled(enable);
        pbEdit.setEnabled(enable);
        pbExecute.setEnabled(getMode()==MODE_EXECUTE && enable);
    }

    public int getMode() { return __mode; }

    private static class HTMLHeader extends HTML {
        public HTMLHeader() {
            super();
            addStyleDependentName("header");
        }
        public HTMLHeader(String text) {
            super(text);
            addStyleDependentName("header");
        }
    }


}
