/*
 * Copyright (C) 2002-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.formbuilder.ui.editors;


import com.arsdigita.formbuilder.WidgetLabel;

import com.arsdigita.bebop.FormData;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.FormSection;
import com.arsdigita.bebop.Label;
import com.arsdigita.bebop.PageState;

import com.arsdigita.bebop.event.FormSectionEvent;

import com.arsdigita.bebop.form.TextArea;
import com.arsdigita.bebop.form.TextField;

import com.arsdigita.bebop.parameters.StringParameter;

import com.arsdigita.domain.DataObjectNotFoundException;

import com.arsdigita.formbuilder.PersistentWidget;


import java.math.BigDecimal;
import com.arsdigita.formbuilder.PersistentFormSection;
import com.arsdigita.bebop.SingleSelectionModel;
import com.arsdigita.formbuilder.PersistentLabel;
import com.arsdigita.bebop.parameters.NotNullValidationListener;
import com.arsdigita.bebop.parameters.StringInRangeValidationListener;
import com.arsdigita.bebop.ColumnPanel;
import com.arsdigita.bebop.form.Widget;
import com.arsdigita.formbuilder.util.GlobalizationUtil ; 
import com.arsdigita.globalization.GlobalizedMessage;


public abstract class WidgetLabelForm extends WidgetForm {
    private Widget m_label;


    public WidgetLabelForm(String name,
                           SingleSelectionModel form,
                           SingleSelectionModel control) {
        super(name, form, control);
    }

    protected void addWidgets(FormSection section) {

        if (wantLabelMultiline()) {
            TextArea text = new TextArea(new StringParameter("label"));
            text.setCols(30);
            text.setRows(10);
            text.addValidationListener(new NotNullValidationListener());
            text.addValidationListener(new StringInRangeValidationListener(1, 4000));
            m_label = text;
        } else {
            TextField text = new TextField(new StringParameter("label"));
            text.setSize(30);
            text.addValidationListener(new NotNullValidationListener());
            text.addValidationListener(new StringInRangeValidationListener(1, 4000));
            m_label = text;
        }

        m_label.setOnFocus("if (this.form." + NAME + ".value == '') { " +
                           " defaulting = true; this.form." + NAME +
                           ".value = urlize(this.value); }");
        m_label.setOnKeyUp(
            "if (defaulting) { this.form." + NAME +
            ".value = urlize(this.value) }"
            );

        section.add(new Label(getLabelText()), ColumnPanel.RIGHT);
        section.add(m_label);

        super.addWidgets(section);

        automaticallySetName(m_label.getParameterModel());
    }

    /**
     *  @deprecated used getGlobalizedLabelText()
     */
    protected String getLabelText() {
        return (String)getGlobalizedLabelText().localize();
    }

    protected GlobalizedMessage getGlobalizedLabelText() {
        return GlobalizationUtil.globalize("formbuilder.ui.editors.label");
    }

    protected boolean wantLabelMultiline() {
        return false;
    }

    protected void initWidgets(FormSectionEvent e,
                               PersistentWidget widget)
        throws FormProcessException {

        super.initWidgets(e, widget);

        PageState state = e.getPageState();

        if (widget != null) {
            WidgetLabel l = null;
            try {
                l = WidgetLabel.findByWidget(widget);
            } catch (DataObjectNotFoundException ex) {
                throw new FormProcessException("cannot find label for WidgetLabel");
            }

            m_label.setValue(state, l.getLabel());
        } else {
            m_label.setValue(state, "");
        }
    }

    protected void processWidgets(FormSectionEvent e,
                                  PersistentWidget widget)
        throws FormProcessException {

        super.processWidgets(e, widget);

        FormData data = e.getFormData();

        String label = (String)data.get("label");

        if (widget.isNew())
            return;

        PersistentLabel l = null;
        try {
            l = WidgetLabel.findByWidget(widget);
        } catch (DataObjectNotFoundException ex) {
            throw new FormProcessException("cannot find label for WidgetLabel");
        }

        l.setLabel(label);
        l.save();
    }

    protected void addToForm(FormSectionEvent e,
                             PersistentWidget widget)
        throws FormProcessException {

        FormData data = e.getFormData();

        String label = (String)data.get("label");

        BigDecimal form_id = (BigDecimal)getSelection().getSelectedKey(e.getPageState());

        PersistentFormSection form = null;
        try {
            form = new PersistentFormSection(form_id);
        } catch (DataObjectNotFoundException ex) {
            throw new FormProcessException("cannot find form",ex);
        }

        addWidgetLabel(widget, label, form);

        // We could call super.addToForm at this point,
        // however since we already have a Form object
        // constructed its more efficient for us to do
        // it ourselves
        form.addComponent(widget);

        form.save();
    }

    /**
     *  this provides subclasses with the ability to add the widget label
     *  in any manner they see fit.  Specifically, it allows them to
     *  use a sublcass of WidgetLabel or to make this is no-op so that the
     *  this step is ignored if needed.
     *
     *  This will return null if not label is actually added.
     */
    protected WidgetLabel addWidgetLabel(PersistentWidget widget,
                                         String label,
                                         PersistentFormSection form) {
        WidgetLabel l = WidgetLabel.create(widget,
                                           label);
        l.save();
        form.addComponent(l);
        return l;
    }
}
