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

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.app.vo.TextboxFieldData;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.controls.QFormElementControllerImpl;
import com.queplix.core.client.controls.QFormElementModel;
import com.queplix.core.client.controls.QFormElementView;

class QTextBoxControllerImpl extends QFormElementControllerImpl
        implements QTextBoxController,
        ChangeListener {
    private QTextBoxModelImpl model;
    private QTextBoxViewImpl view;
    private boolean ignoreTextChangeEvent;

    public QTextBoxControllerImpl(QTextBoxModelImpl model,
                                  QTextBoxViewImpl view) {
        this.model = model;
        this.view = view;
        this.view.addTextChangeListener(this);
        this.view.addKeyboardListener(new KeyboardListener() {
            public void onKeyDown(Widget sender, char keyCode, int modifiers) {
            }

            public void onKeyPress(Widget sender, char keyCode, int modifiers) {
            }

            public void onKeyUp(Widget sender, char keyCode, int modifiers) {
                onChange(sender);
            }
        });
    }

    public void onChange(Widget sender) {
        if(!ignoreTextChangeEvent) {
            String newText = ((TextBoxBase) sender).getText();
            ignoreTextChangeEvent = true;

            newText = StringUtil.nullToEmpty(newText);
            TextboxFieldData tfd = model.getData();
            String text = tfd.getText();
            if(!newText.equalsIgnoreCase(text)) {
                tfd.setText(newText);
                model.setData(tfd);
            }

            ignoreTextChangeEvent = false;
        }
    }

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

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

}