/*
 * Copyright (C) 2001-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.cms.ui.templates;


import com.arsdigita.bebop.FormData;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.Label;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.form.TextField;
import com.arsdigita.bebop.parameters.NotNullValidationListener;
import com.arsdigita.bebop.parameters.TrimmedStringParameter;
import com.arsdigita.cms.ContentItem;
import com.arsdigita.cms.Folder;
import com.arsdigita.cms.ItemSelectionModel;
import com.arsdigita.cms.Template;
import com.arsdigita.cms.ui.authoring.AuthoringKitWizard;
import com.arsdigita.cms.ui.authoring.BasicPageForm;
import com.arsdigita.cms.ui.authoring.NameValidationListener;
import com.arsdigita.cms.ui.authoring.SimpleEditStep;
import com.arsdigita.cms.ui.workflow.WorkflowLockedComponentAccess;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.toolbox.ui.DomainObjectPropertySheet;
import com.arsdigita.util.Assert;
import org.apache.log4j.Logger;

/**
 * The template editing component. Consists of a display component
 * which displays the name/title of the template, and a form which edits
 * those properties.
 *
 * @author Stanislav Freidin (sfreidin@arsdigita.com)
 * @version $Revision: #9 $ $DateTime: 2004/04/07 16:07:11 $
 */
public class TemplateEdit extends SimpleEditStep {

    public static final String versionId = "$Id: //cms/dev/src/com/arsdigita/cms/ui/templates/TemplateEdit.java#9 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private static Logger s_log =
        Logger.getLogger(TemplateEdit.class);

    /**
     * Construct a new TemplateEdit component
     *
     * @param itemModel The {@link ItemSelectionModel} which will
     *   be responsible for loading the current item
     *
     * @param parent The parent wizard which contains the form. The form
     *   may use the wizard's methods, such as stepForward and stepBack,
     *   in its process listener.
     */
    public TemplateEdit(ItemSelectionModel itemModel, AuthoringKitWizard parent) {
        super(itemModel, parent);

        TemplateEditForm form = new TemplateEditForm(itemModel);
        add("edit", "Edit", new WorkflowLockedComponentAccess(form, itemModel),
            form.getSaveCancelSection().getCancelButton());

        //DomainObjectPropertySheet sheet = new DomainObjectPropertySheet(itemModel);
        DomainObjectPropertySheet sheet = new DomainObjectPropertySheet(itemModel, false);
        sheet.add((String) GlobalizationUtil.globalize("cms.ui.templates.name").localize(),  ContentItem.NAME);
        sheet.add((String) GlobalizationUtil.globalize("cms.ui.templates.label").localize(),  Template.LABEL);

        setDisplayComponent(sheet);
    }

    /**
     * A form for editing Template basic properties
     */
    private class TemplateEditForm extends BasicPageForm {

        /**
         * Construct a new TemplateEditForm
         *
         * @param itemModel The {@link ItemSelectionModel} which will
         *   be responsible for loading the current item
         *
         */
        public TemplateEditForm(ItemSelectionModel itemModel) {
            super("TemplateEditForm", itemModel);
        }

        /**
         * Create the widgets for this form
         */
        protected void addWidgets() {
            add(new Label(GlobalizationUtil.globalize("cms.ui.templates.name")));
            TextField nameWidget =
                new TextField(new TrimmedStringParameter(NAME));
            nameWidget.addValidationListener(new NameValidationListener());
            add(nameWidget);

            add(new Label(GlobalizationUtil.globalize("cms.ui.templates.label")));
            TextField labelWidget =
                new TextField(new TrimmedStringParameter(Template.LABEL));
            labelWidget.addValidationListener(new NotNullValidationListener());
            add(labelWidget);
        }

        // Init: load the item and preset the widgets
        public void init(FormSectionEvent e) throws FormProcessException {
            FormData data = e.getFormData();
            PageState state = e.getPageState();
            Template t = getTemplate(state);
            // Preset fields
            data.put(ContentItem.NAME, t.getName());
            data.put(Template.LABEL, t.getLabel());
        }

        // Process: save fields to the database
        public void process(FormSectionEvent e) throws FormProcessException {
            FormData data = e.getFormData();
            PageState state = e.getPageState();
            Template t = getTemplate(state);
            t.setName((String)data.get(NAME));
            t.setLabel((String)data.get(Template.LABEL));
            t.save();
        }

        public void validate(FormSectionEvent event) throws FormProcessException {
            PageState state = event.getPageState();
            FormData data = event.getFormData();
            Template t = getTemplate(state);

            String newName = (String)data.get(NAME);
            String oldName = t.getName();

            // Validation passes if the item name is the same.
            if ( !newName.equalsIgnoreCase(oldName) ) {
                validateNameUniqueness((Folder)t.getParent(), event);
            }
        }

        // Get the current template
        public Template getTemplate(PageState state) {
            Template t =
                (Template) getItemSelectionModel().getSelectedObject(state);
            Assert.assertNotNull(t);
            return t;
        }
    }

}
