/*
 * Copyright
 *   2008 axYus - www.axyus.com
 *   2008 C.Bosquet - charles.bosquet@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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU 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.criteria;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.InputCritereItemDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.LabelValueDTO;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.Property;
import fr.gouv.finances.dgfip.xemelios.web.gwt.client.dto.SelectOneCritereItemDTO;
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.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CBO
 * Permet de choisir une valeur parmi plusieurs
 */
public class SelectOneCritereWidget extends InputCritereWidget {

    private SelectOneCritereItemDTO selectOneCritereItem;
    private ListBox listBox;

    public SelectOneCritereWidget(final CritereLineContainer critereLineContainer, final SelectOneCritereItemDTO selectOneCritereItem) {
        super(critereLineContainer, selectOneCritereItem);
        this.selectOneCritereItem = selectOneCritereItem;
        this.listBox = new ListBox();
        fillListBox(selectOneCritereItem.getItems(), selectOneCritereItem.getSelectedItem());
        if (!selectOneCritereItem.getCriteresDependants().isEmpty()) {
            addChangeListener(new ChangeListener() {

                public void onChange(Widget widget) {
                    for (InputCritereItemDTO inputCritereItemDTO : selectOneCritereItem.getCriteresDependants()) {
                        InputCritereWidget dependantInputCritereWidget = critereLineContainer.getInputCritereWidget(inputCritereItemDTO.getInputId());
                        dependantInputCritereWidget.refresh();
                    }

                }
            });
        }
        if(selectOneCritereItem.getLastInputValue()!=null) {
            String lastValue = selectOneCritereItem.getLastInputValue();
            for(int i=0;i<listBox.getItemCount();i++) {
                if(listBox.getValue(i).equals(lastValue)) {
                    listBox.setSelectedIndex(i);
                    break;
                }
            }
        }
        initWidget(listBox);
    }
    public SelectOneCritereWidget(final CritereLineContainer critereLineContainer, final SelectOneCritereItemDTO selectOneCritereItem,List<Property> properties) {
        super(critereLineContainer, selectOneCritereItem);
        this.selectOneCritereItem = selectOneCritereItem;
        this.listBox = new ListBox();
        fillListBox(selectOneCritereItem.getItems(), selectOneCritereItem.getSelectedItem());
        if (!selectOneCritereItem.getCriteresDependants().isEmpty()) {
            addChangeListener(new ChangeListener() {

                public void onChange(Widget widget) {
                    for (InputCritereItemDTO inputCritereItemDTO : selectOneCritereItem.getCriteresDependants()) {
                        InputCritereWidget dependantInputCritereWidget = critereLineContainer.getInputCritereWidget(inputCritereItemDTO.getInputId());
                        dependantInputCritereWidget.refresh();
                    }

                }
            });
        }
        String lastValue = null;
        for(Property  prop: properties) {
            if(prop.getName().equals(getInputId())) {
                lastValue = prop.getValue();
            }
        }
        if(lastValue==null) {
            lastValue = selectOneCritereItem.getLastInputValue();
        }
        if(lastValue!=null) {
            for(int i=0;i<listBox.getItemCount();i++) {
                if(listBox.getValue(i).equals(lastValue)) {
                    listBox.setSelectedIndex(i);
                    break;
                }
            }
        }
        initWidget(listBox);
    }

    private void updateListBoxContent(List<LabelValueDTO> items, LabelValueDTO selectedItem) {
        selectOneCritereItem.setItems(items);
        selectOneCritereItem.setSelectedItem(selectedItem);
        fillListBox(items, selectedItem);
    }

    public void fillListBox(Collection<LabelValueDTO> labelValues, LabelValueDTO selectedItem) {
        listBox.clear();
        int index = 0;
        for (LabelValueDTO labelValue : labelValues) {
            listBox.addItem(labelValue.getLabel(), labelValue.getValue());
            if (labelValue.equals(selectOneCritereItem.getSelectedItem())) {
                listBox.setSelectedIndex(index);
            }
            index++;
        }
    }

    public void addChangeListener(ChangeListener changeListener) {
        listBox.addChangeListener(changeListener);
    }

    @Override
    public void checkValidity() throws ValidityException {
        
    }

    @Override
    public void setFocus() {
        this.listBox.setFocus(true);
    }

    @Override
    public String getInputId() {
        return this.selectOneCritereItem.getInputId();
    }

    @Override
    public String getInputValue() {
        return listBox.getValue(listBox.getSelectedIndex());
    }

    @Override
    public void refresh() {
        Map<String, String> inputValues = new HashMap<String, String>();
        for (InputCritereItemDTO criteresMaitre : selectOneCritereItem.getCriteresMaitres()) {
            InputCritereWidget inputWidget = getCritereLineContainer().getInputCritereWidget(criteresMaitre.getInputId());
            inputValues.put(inputWidget.getInputId(), inputWidget.getInputValue());
            ServiceLocator.getXemeliosService().getUpdatedSelectOneCritereItemDTO(
                    getCritereLineContainer().getCriteriaTable().getMainWidget().getSearchSessionId(),
                    getCritereLineContainer().getCriteriaTable().getMainWidget().getCollectiviteId(),
                    getCritereLineContainer().getCriteriaTable().getMainWidget().getBudgetId(),
                    getCritereLineContainer().getCritereId(),
                    getInputId(),
                    inputValues,
                    getCritereLineContainer().getCriteriaTable().getPluginId(),
                    new AsyncCallback<SelectOneCritereItemDTO>() {

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

                        public void onSuccess(SelectOneCritereItemDTO result) {
                            if (result != null) {
                                updateListBoxContent(result.getItems(), result.getSelectedItem());
                            }
                        }
                    });
        }
    }
}
