/*
 * Copyright
 *   2007 axYus - www.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.search;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
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.ChangeListenerCollection;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.LabelValueDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.service.ServiceLocator;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.utils.GWTUtils;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.widget.navigate.DlgSelectCollectivite;
import java.util.List;

/**
 * @author CBO
 * Widget permettant à l'utilisateur de choisir la collectivité et le budget
 */
public class ColAndBudChooserWidget extends Composite implements ColAndBudListener {

    private SearchWidget searchWidget;
    private ListBox collectivitesListBox;
    private ListBox budgetListBox;
    private ChangeListenerCollection changeListeners;
    private HorizontalPanel divMain;
    private TextBox dfCollectivite;
    private Button pbHelpCollectivite;
    private LabelValueDTO collectivite;

    public ColAndBudChooserWidget(final SearchWidget searchWidget) {
        this.searchWidget = searchWidget;
        this.collectivitesListBox = new ListBox();
        this.budgetListBox = new ListBox();
        this.changeListeners = new ChangeListenerCollection();
        collectivitesListBox.addChangeListener(new ChangeListener() {

            public void onChange(Widget widget) {
                collectiviteChange();
            }
        });
        budgetListBox.addChangeListener(new ChangeListener() {

            public void onChange(Widget widget) {
                budgetChange();
            }
        });
        collectivitesListBox.addStyleName("limitedWidth");
        budgetListBox.addStyleName("limitedWidth");

        HorizontalPanel mainPanel = new HorizontalPanel();
        mainPanel.getElement().setId("NavigationTools");
        mainPanel.setStyleName("ToolBar");
        mainPanel.add(new Image(GWTUtils.getContextPath()+"/img/toolbar-left.gif"));
        divMain = new HorizontalPanel();
        divMain.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);
        mainPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);
        divMain.addStyleName("Main");
        divMain.add(new InlineHTML("Collectivit&eacute; : "));
        divMain.add(collectivitesListBox);
        divMain.add(new InlineHTML("Budget : "));
        divMain.add(budgetListBox);
        mainPanel.add(divMain);
        mainPanel.add(new Image(GWTUtils.getContextPath()+"/img/toolbar-right.gif"));

        initWidget(mainPanel);
    }

    public void init(List<LabelValueDTO> collectivites, List<LabelValueDTO> budgets) {
        this.collectivitesListBox.clear();
        for (LabelValueDTO lblCollectivite : collectivites) {
            collectivitesListBox.addItem(lblCollectivite.getLabel(), lblCollectivite.getValue());
        }
        for (LabelValueDTO budget : budgets) {
            budgetListBox.addItem(budget.getLabel(), budget.getValue());
        }
        if(collectivitesListBox.getItemCount()>0)
            collectivitesListBox.setSelectedIndex(0);
        NodeList<Element> options = collectivitesListBox.getElement().getElementsByTagName("option");
        for(int i=0;i<options.getLength();i++) {
            Element option = options.getItem(i);
            option.setAttribute("style", "width: auto;");
        }
    }
    // when there is too much collectivities
    public void init(String documentId) {
        divMain.clear();
        collectivitesListBox = null;
        dfCollectivite = new TextBox();
//        dfCollectivite.setWidth("100%");
        dfCollectivite.addStyleName("limitedWidth");
        dfCollectivite.setReadOnly(true);
        divMain.add(new InlineHTML("Collectivit&eacute; : "));
        divMain.add(dfCollectivite);
        final String docId = documentId;
        pbHelpCollectivite = new Button("...",new ClickListener() {
            public void onClick(Widget sender) {
                pbHelpCollectivitesClicked(docId);
            }
        });
        pbHelpCollectivite.addStyleName("helpCollectivite");
        divMain.add(pbHelpCollectivite);
        divMain.add(new InlineHTML("Budget : "));
        divMain.add(budgetListBox);
    }

    protected void pbHelpCollectivitesClicked(String documentId) {
        new DlgSelectCollectivite(documentId, this);
    }

    public String getCollectiviteId() {
        if(collectivitesListBox!=null) {
            if(collectivitesListBox.getSelectedIndex()>=0)
                return collectivitesListBox.getValue(collectivitesListBox.getSelectedIndex());
            else return null;
        } else {
            return collectivite!=null ? collectivite.getId() : null;
        }
    }

    public String getBudgetId() {
        return budgetListBox.getValue(budgetListBox.getSelectedIndex());
    }

    public void addChangeListener(ChangeListener changeListener) {
        this.changeListeners.add(changeListener);
    }

    private void collectiviteChange() {
        ServiceLocator.getXemeliosService().getBudgets(searchWidget.getSearchSessionId(), getCollectiviteId(), new AsyncCallback<List<LabelValueDTO>>() {

            public void onFailure(Throwable throwable) {
                GWTUtils.handleRPCError(throwable);
            }

            public void onSuccess(List<LabelValueDTO> budgets) {
                budgetListBox.clear();
                for (LabelValueDTO budget : budgets) {
                    budgetListBox.addItem(budget.getLabel(), budget.getValue());
                }
                NodeList<Element> options = budgetListBox.getElement().getElementsByTagName("option");
                for(int i=0;i<options.getLength();i++) {
                    Element option = options.getItem(i);
                    option.setAttribute("style", "width: auto;");
                }
                fireOnchange();
            }
        });
    }

    private void budgetChange() {
        fireOnchange();
        searchWidget.resetCriteres();
    }

    private void fireOnchange() {
        this.changeListeners.fireChange(this);
    }

    public void setCollectivite(LabelValueDTO collectivite) {
        this.collectivite = collectivite;
        dfCollectivite.setText(this.collectivite.getLibelle());
        collectiviteChange();
    }
}
