/*
 * 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.DOM;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.queplix.core.client.common.StringUtil;

class QTextBoxViewImpl extends QTextBoxView {
    private QTextBoxModelImpl model;
    private TextBoxBase textbox;

    public QTextBoxViewImpl(QTextBoxModelImpl model, int layout,
                            boolean masked) {
        super(model, layout);
        this.model = model;
        initializeUI(masked);
    }

    private void initializeUI(boolean masked) {
        if(masked) {
            textbox = new PasswordTextBox();
        } else {
            textbox = new TextBox();
        }
        textbox.setText(model.getData().getText());
        textbox.addStyleName("styled_input");
        HorizontalPanel fieldPanel = new HorizontalPanel();
        fieldPanel.add(textbox);
        fieldPanel.add(emptyButton);
        addToPanel(fieldPanel);
        initPanel();
    }

    public void onModelDataChanged() {
        super.onModelDataChanged();
        String modelText = model.getData().getText();
        String emptyToNullText = StringUtil.nullToEmpty(modelText);
        if(!textbox.getText().equalsIgnoreCase(emptyToNullText)) {
            textbox.setText(emptyToNullText);
        }
    }

    void addKeyboardListener(KeyboardListener keyboardListener) {
        textbox.addKeyboardListener(keyboardListener);
    }

    void addTextChangeListener(ChangeListener listener) {
        textbox.addChangeListener(listener);
    }

    protected void setEnabled(boolean isEnabled) {
        String readOnly = isEnabled ? null:"readonly";
        DOM.setAttribute(textbox.getElement(), "readOnly", readOnly);
    }

    protected void setClientWidth(String clientWidth) {
        textbox.setWidth(clientWidth);
    }

    public int getClientWidth() {
        return textbox.getOffsetWidth();
    }

    public int getFilledWidth() {
        return super.getFilledWidth() + emptyButton.getOffsetWidth() - 1;
    }
}