/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.client.controls.listbox;

import com.queplix.core.client.app.vo.ListboxDataRequest;
import com.queplix.core.client.app.vo.ListboxFieldData;
import com.queplix.core.client.app.vo.SubsetData;
import com.queplix.core.client.controls.QFormElementControllerImpl;
import com.queplix.core.client.controls.QFormElementModel;
import com.queplix.core.client.controls.QFormElementView;

class QListBoxControllerImpl extends QFormElementControllerImpl
        implements QListBoxController, ListSelectionListener {
    private QListBoxModelImpl model;
    private QListBoxViewImpl view;

    private ListboxDataRequest request;

    public QListBoxControllerImpl(QListBoxModelImpl model,
                                  QListBoxViewImpl view) {
        this.model = model;
        this.view = view;

        subscribeEvents();
    }

    private void subscribeEvents() {
        view.addChangeListener(this);
    }

    public void selectionChanged(int[] selectedIndexes) {
        long ids[] = new long[selectedIndexes.length];
        ListboxFieldData lfd = model.getData();
        for(int i = 0; i < selectedIndexes.length; i++) {
            if(selectedIndexes[i] == -1) {
                ids[i] = -1;
            } else {
                ids[i] = model.getMeta().getAvailableChoises()
                        .getItems()[selectedIndexes[i]].getId();
            }
        }
        lfd.setItemsSelected(new SubsetData(ids));
        model.setData(lfd);
    }

    public void popupDemanded() {
        if(model.getMeta().isDynamic()) {
            if(request == null) {
                request = new ListboxDataRequest(
                        model.getBaseMeta().getFieldID(),
                        model.getMeta().getReferencingEntityName(), null);
            }
            controlEventsListener.needMoreData(request);
        }
    }

    public QFormElementModel getModel() {
        return this.model;
    }

    public QFormElementView getView() {
        return this.view;
    }
}
