/*
 * 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.multiselect;

import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.app.vo.MultiselectDataRequest;
import com.queplix.core.client.common.event.Event;
import com.queplix.core.client.common.event.EventListener;
import com.queplix.core.client.controls.QFormElementControllerImpl;
import com.queplix.core.client.controls.QFormElementModel;
import com.queplix.core.client.controls.QFormElementView;

/**
 * Class represents DateField controller.
 *
 * @author Sergey Kozmin
 * @since 14.09.2006
 */
class QMultiSelectControllerImpl extends QFormElementControllerImpl
        implements QMultiSelectController, EventListener {
    private QMultiSelectViewImpl view;
    private QMultiSelectModelImpl model;

    private MultiselectDataRequest request;

    QMultiSelectControllerImpl(QMultiSelectViewImpl view,
                               QMultiSelectModelImpl model) {
        this.view = view;
        this.model = model;
        view.addListener(this);
    }

    public QFormElementModel getModel() {
        return model;
    }

    public QFormElementView getView() {
        return view;
    }

    public void onEvent(Event event, Widget sender) {
        if(event == QMultiSelectView.Events.OK) {
            if(!view.isDisabled()) {
                model.getData().setItemsSelected(view.getDialogItemsSelected());
                model.fireModelChanged();
            }
        } else if(event == QMultiSelectView.Events.ON_DIALOG_DEMAND) {
            if(model.getMeta().isDynamic()) {
                if(request == null) {
                    request = new MultiselectDataRequest(
                            model.getBaseMeta().getFieldID(),
                            model.getMeta().getReferencingEntityName(), null);
                }
                controlEventsListener.needMoreData(request);
            } else {
                view.showDialog();
            }
        }
    }
}

