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

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.queplix.core.client.common.StringUtil;
import com.queplix.core.client.controls.QElementsCoupler;
import com.queplix.core.client.controls.QFormElementModelImpl;
import com.queplix.core.client.controls.QFormElementView;

import java.util.ArrayList;
import java.util.List;

/**
 * QTextAreaViewImpl.
 *
 * @author Sergey Kozmin
 * @since 27 Sep 2006
 */
class QTextAreaViewImpl extends QTextAreaView implements
        FocusListener,
        QFormElementModelImpl.ModelListener,
        ChangeListener {
    private QTextAreaModelImpl model;
    private TextArea textArea;

    private boolean isUserUpdate = false;

    private List changeListeners = new ArrayList();

    public QTextAreaViewImpl(QTextAreaModelImpl model, int layout, int width,
                             int height) {
        super(model, layout);
        this.model = model;
        initializeUI(width, height);
        initializeListeners();
    }

    private void initializeUI(int width, int height) {
        HorizontalPanel fieldPanel = new HorizontalPanel();
        textArea = new TextArea();
        textArea.addStyleName("styled_input");
        textArea.setCharacterWidth(width);
        textArea.setVisibleLines(height);
        textArea.setText(StringUtil.nullToEmpty(model.getData().getText()));
        fieldPanel.add(textArea);
        fieldPanel.add(emptyButton);
        addToPanel(fieldPanel);
        initPanel();
    }

    private void initializeListeners() {
        model.addModelListener(this);
        textArea.addChangeListener(this);
        textArea.addFocusListener(this);
        textArea.addKeyboardListener(new KeyboardListener() {
            private String text;

            public void onKeyDown(Widget sender, char keyCode, int modifiers) {
                if(!textArea.getText().equals(text)) {
                    onChange(textArea);
                }
            }

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

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

    public void addTextChangeListener(TextListener listener) {
        changeListeners.add(listener);
    }

    public void removeTextChangeListener(TextListener listener) {
        changeListeners.remove(listener);
    }

    protected void fireTextChangedPerformed(String text) {
        if(changeListeners != null) {
            for(int i = 0; i < changeListeners.size(); i++) {
                TextListener listener = (TextListener) changeListeners.get(i);
                listener.testChanged(text);
            }
        }
    }

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

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

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

    public void setRowSpan(int rowSpan) {
        super.setRowSpan(rowSpan);
        if(isVerticalLayout()) {
            textArea.setVisibleLines(rowSpan > 1 ? Math.round(rowSpan * 2.2f)
                    - 1:4);
        } else {
            textArea.setVisibleLines(rowSpan > 1 ? rowSpan + 2:4);
        }
    }

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

    public void onFocus(Widget sender) {
        if(sender == textArea) {
            getEventSource().fireEvent(
                    QFormElementView.Events.TEXTAREA_FOCUSED);
        }
    }

    public void onLostFocus(Widget sender) {
        if(sender == textArea) {
            getEventSource().fireEvent(
                    QFormElementView.Events.TEXTAREA_FOCUS_LOST);
        }
    }

    public void onModelDataChanged() {
        setupIndicatorState();
        if(!isUserUpdate) {
            textArea.setText(StringUtil.nullToEmpty(model.getData().getText()));
        }
    }

    public void onModelMetaChanged() {
        setCaption(model.getMeta().getCaption());
    }

    public void onDemandModelChanged() {
    }

    public void onChange(Widget sender) {
        if(sender == textArea) {
            isUserUpdate = true;
            fireTextChangedPerformed(textArea.getText());
            isUserUpdate = false;
        }
    }

    public boolean canBeCoupled(int coupleType) {
        return coupleType == QElementsCoupler.LEFT_ITEM;
    }
}