/*
 * 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.queplix.core.client.app.vo.TextareaFieldData;
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;

import java.util.ArrayList;

class QTextAreaControllerImpl extends QFormElementControllerImpl
        implements QTextAreaController, QTextAreaChangeListener, TextListener {

    private QTextAreaModelImpl model;
    private QTextAreaViewImpl view;
    private ArrayList changeListeners;

    public QTextAreaControllerImpl(QTextAreaModelImpl model,
                                   QTextAreaViewImpl view) {
        this.model = model;
        this.view = view;

        subscribeEvents();
    }

    private void subscribeEvents() {
        model.addDataChangeListener(this);
        view.addTextChangeListener(this);
    }

    public void dataChanged() {
        fireTextChangedPerformed();
    }

    public void addTextChangeListener(QTextAreaChangeListener listener) {
        if(changeListeners == null) {
            changeListeners = new ArrayList();
        }
        changeListeners.add(listener);
    }

    public void removeTextChangeListener(QTextAreaChangeListener listener) {
        if(changeListeners != null) {
            changeListeners.remove(listener);
        }
    }

    protected void fireTextChangedPerformed() {
        if(changeListeners != null) {
            for(int i = 0; i < changeListeners.size(); i++) {
                QTextAreaChangeListener listener
                        = (QTextAreaChangeListener) changeListeners.get(i);
                listener.dataChanged();
            }
        }
    }

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

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

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