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

import com.arsdigita.bebop.ColumnPanel;
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.event.FormSubmissionListener;
import com.arsdigita.cms.ContentBundle;
import com.arsdigita.cms.ContentPage;
import com.arsdigita.cms.ContentSection;
import com.arsdigita.cms.ContentType;
import com.arsdigita.cms.Folder;
import com.arsdigita.cms.ItemSelectionModel;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.util.Assert;
import java.util.Date;

import org.apache.log4j.Logger;

/**
 * A form which will create a new ContentPage or one of its
 * subclasses.
 *
 * @author Stanislav Freidin (stas@arsdigita.com)
 * @version $Revision: #20 $ $DateTime: 2004/04/07 16:07:11 $
 */
public class PageCreate extends BasicPageForm
        implements FormSubmissionListener, CreationComponent {
    public static final String versionId =
        "$Id: //cms/dev/src/com/arsdigita/cms/ui/authoring/PageCreate.java#20 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger(PageCreate.class);

    private final CreationSelector m_parent;
    private ApplyWorkflowFormSection m_workflowSection;

    /**
     * The state parameter which specifies the content section
     */
    public static final String SECTION_ID = "sid";

    /**
     * Construct a new PageCreationForm
     *
     * @param itemModel The {@link ItemSelectionModel} which will be
     * responsible for loading the current item
     *
     * @param parent The {@link CreationSelector} parent. This class
     * should call either the {@link
     * CreationSelector#redirectBack(PageState)} or {@link
     * CreationSelector#editItem(PageState, ContentItem)} methods on
     * the parent eventually
     */
    public PageCreate(final ItemSelectionModel itemModel,
                      final CreationSelector parent) {
        super("PageCreate", itemModel);
        
        m_parent = parent;
        m_workflowSection.setCreationSelector(m_parent);
        addSubmissionListener(this);

        getSaveCancelSection().getSaveButton().setButtonLabel("Create");
    }

    /**
     * Add various widgets to the form. Child classes should override
     * this method to perform all their widget-adding needs.
     */
    protected void addWidgets() {
        ContentType type = getItemSelectionModel().getContentType();
        m_workflowSection = new ApplyWorkflowFormSection(type);
        add(m_workflowSection, ColumnPanel.INSERT);
        add(new Label(GlobalizationUtil.globalize("cms.ui.authoring.content_type")));
        add(new Label(type.getLabel()));
        add(new Label(GlobalizationUtil.globalize("cms.ui.language.field")));
        add(new LanguageWidget(LANGUAGE));
        super.addWidgets();
    }

    /**
     * Return the ApplyWorkflowFormSection associated with this CreationComponent.
     *
     * @return the ApplyWorkflowFormSection associated with this CreationComponent.
     */
    public ApplyWorkflowFormSection getWorkflowSection() {
        return m_workflowSection;
    }

    // Init: create a new item id
    public void init(FormSectionEvent e) throws FormProcessException {
        // this is currently a no-op
    }

    // Submission: If the Cancel button was pressed, hide self and
    // show the display component
    public void submitted(FormSectionEvent e) throws FormProcessException {
        PageState state = e.getPageState();

        if(getSaveCancelSection().getCancelButton().isSelected(state)) {
            m_parent.redirectBack(state);

            throw new FormProcessException
                ((String) GlobalizationUtil.globalize
                     ("cms.ui.authoring.submission_cancelled").localize());
        }
    }

    // Validate: ensure name uniqueness
    public void validate(FormSectionEvent e) throws FormProcessException {
        Folder f = m_parent.getFolder(e.getPageState());
        Assert.assertNotNull(f);
        validateNameUniqueness(f, e);
    }

    // Process: save fields to the database
    public void process(final FormSectionEvent e) throws FormProcessException {
        final FormData data = e.getFormData();
        final PageState state = e.getPageState();
        final ContentSection section = m_parent.getContentSection(state);
        Folder folder = m_parent.getFolder(state);

        Assert.exists(section, ContentSection.class);

        final ContentPage item = createContentPage(state);
        item.setLanguage((String) data.get(LANGUAGE));
        item.setName((String) data.get(NAME));
        item.setTitle((String) data.get(TITLE));
        if (!ContentSection.getConfig().getHideLaunchDate()) {
            item.setLaunchDate((Date) data.get(LAUNCH_DATE));
        }

        final ContentBundle bundle = new ContentBundle(item);
        bundle.setParent(folder);
        bundle.setContentSection(m_parent.getContentSection(state));
        bundle.save();

        m_workflowSection.applyWorkflow(state, item);

        m_parent.editItem(state, item);
    }

}
