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


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.SimpleContainer;
import com.arsdigita.bebop.event.FormInitListener;
import com.arsdigita.bebop.event.FormProcessListener;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.event.PrintEvent;
import com.arsdigita.bebop.event.PrintListener;
import com.arsdigita.bebop.form.Hidden;
import com.arsdigita.bebop.form.Option;
import com.arsdigita.bebop.form.SingleSelect;
import com.arsdigita.bebop.form.Submit;
import com.arsdigita.bebop.form.TextArea;
import com.arsdigita.bebop.form.TextField;
import com.arsdigita.bebop.parameters.BigDecimalParameter;
import com.arsdigita.bebop.parameters.NotNullValidationListener;
import com.arsdigita.bebop.parameters.StringLengthValidationListener;
import com.arsdigita.bebop.parameters.StringParameter;
import com.arsdigita.cms.CMS;
import com.arsdigita.cms.ContentSection;
import com.arsdigita.cms.ContentType;
import com.arsdigita.cms.ContentTypeLifecycleDefinition;
import com.arsdigita.cms.dispatcher.Utilities;
import com.arsdigita.cms.lifecycle.LifecycleDefinition;
import com.arsdigita.cms.lifecycle.LifecycleDefinitionCollection;
import com.arsdigita.cms.ui.CMSForm;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.db.Sequences;
import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.persistence.OID;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.util.UncheckedWrapperException;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.TooManyListenersException;


/**
 * This class contains a form component to add a content type
 *
 * @author Jack Chung (flattop@arsdigita.com)
 * @version $Revision: #14 $ $Date: 2004/04/07 $
 */
public class AddType extends CMSForm
    implements PrintListener, FormProcessListener, FormInitListener {

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

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

    protected Hidden m_id;
    protected TextField m_label, m_objectType, m_className;
    protected TextArea m_description;
    protected SingleSelect m_lifecycleSelect;
    protected Submit m_submit;
    protected Submit m_cancel;


    public AddType() {
        super("ContentType");

        m_id = new Hidden(new BigDecimalParameter("id"));
        add(m_id);
        m_id.addValidationListener(new NotNullValidationListener());

        add(new Label(GlobalizationUtil.globalize("cms.ui.type.label")));
        m_label = new TextField(new StringParameter("label"));
        m_label.addValidationListener(new NotNullValidationListener());
        m_label.setSize(40);
        m_label.setMaxLength(1000);
        add(m_label);

        add(new Label(GlobalizationUtil.globalize("cms.ui.description")));
        m_description = new TextArea(new StringParameter("description"));
        m_description.addValidationListener(new StringLengthValidationListener(4000));
        m_description.setCols(40);
        m_description.setRows(5);
        m_description.setWrap(TextArea.SOFT);
        add(m_description);

        // per our ui specs list #35
        // flattop: code put back in.... will be fixed by Xixi
        add(new Label(GlobalizationUtil.globalize("cms.ui.type.object_type")));
        m_objectType = new TextField(new StringParameter("objectType"));
        m_objectType.addValidationListener(new NotNullValidationListener());
        m_objectType.setSize(40);
        m_objectType.setMaxLength(1000);
        add(m_objectType);

        add(new Label(GlobalizationUtil.globalize("cms.ui.type.class_name")));
        m_className = new TextField(new StringParameter("className"));
        m_className.setSize(40);
        m_className.setMaxLength(1000);
        add(m_className);

        add(new Label(GlobalizationUtil.globalize("cms.ui.type.lifecycle")));
        m_lifecycleSelect = new SingleSelect(new BigDecimalParameter("lifecycle"));
        try {
            m_lifecycleSelect.addPrintListener(this);
        } catch (TooManyListenersException e) {
            s_log.warn("Too many listeners", e);
            throw new UncheckedWrapperException(e);
        }
        add(m_lifecycleSelect);

        SimpleContainer s = new SimpleContainer();
        m_submit = new Submit("submit");
        m_submit.setButtonLabel("Save");
        s.add(m_submit);
        m_cancel = new Submit("cancel");
        m_cancel.setButtonLabel("Cancel");
        s.add(m_cancel);
        add(s, ColumnPanel.FULL_WIDTH|ColumnPanel.CENTER);

        addProcessListener(this);
        addInitListener(this);
        addSubmissionListener(new TypeSecurityListener());
    }

    public boolean isCancelled(PageState state) {
        return m_cancel.isSelected(state);
    }

    /**
     * Print listener to generate the select widget for the list of
     * lifecyle definitions
     */
    public void prepare(PrintEvent event) {

        SingleSelect t = (SingleSelect) event.getTarget();

        //get the current content section
        ContentSection section = CMS.getContext().getContentSection();

        t.addOption(new Option("","-- select --"));

        LifecycleDefinitionCollection cycles = section.getLifecycleDefinitions();
        while (cycles.next()) {
            LifecycleDefinition cycle = cycles.getLifecycleDefinition();
            t.addOption(new Option(cycle.getID().toString(), cycle.getLabel()));
        }
    }


    /**
     * Processes the form
     */
    public void process(FormSectionEvent e) throws FormProcessException {
        PageState state = e.getPageState();
        ContentSection section = CMS.getContext().getContentSection();

        FormData data = e.getFormData();
        BigDecimal key = (BigDecimal) data.get(m_id.getName());
        String label = (String) data.get(m_label.getName());
        String description = (String) data.get(m_description.getName());
        String objectType = (String) data.get(m_objectType.getName());
        String className = (String) data.get(m_className.getName());

        BigDecimal lifecycleID = (BigDecimal) data.get(m_lifecycleSelect.getName());

        ContentType contentType;
        boolean isNew = false;

        //check if the object already exists for double click protection
        try {
            contentType = new ContentType(key);
        } catch (DataObjectNotFoundException ex) {
            contentType = new ContentType(SessionManager.getSession().create
                                          (new OID(ContentType.BASE_DATA_OBJECT_TYPE, key)));
            isNew = true;
        }

        contentType.setLabel(label);
        contentType.setDescription(description);
        contentType.setAssociatedObjectType(objectType);
        contentType.setClassName(className);
        contentType.save();

        if (isNew) {
            updateContentTypeAssociation(section, contentType);
        }

        //associated a default lifecycle
        try {
            if (lifecycleID != null) {
                LifecycleDefinition lifecycle = new LifecycleDefinition(lifecycleID);
                ContentTypeLifecycleDefinition.updateLifecycleDefinition(section,
                                                                         contentType, lifecycle);
            } else {
                //remove the association
                ContentTypeLifecycleDefinition.removeLifecycleDefinition(section,
                                                                         contentType);
            }
        } catch (DataObjectNotFoundException ex) {
            //just ignore this since the lifecycle definition does not exist
            // no association
        }

        Utilities.refreshItemUI(state);

    }

    public void init(FormSectionEvent e) {
        FormData data = e.getFormData();
        try {
            if (data.get(m_id.getName()) == null) {
                data.put(m_id.getName(), Sequences.getNextValue());
            }
        } catch (SQLException s) {
            s_log.warn("Error retrieving sequence value", s);
            data.addError("Could not generate Sequence ID " + s.getMessage());
        }
    }

    protected void updateContentTypeAssociation(ContentSection section,
                                                ContentType type) {
        section.addContentType(type);
        section.save();
    }

    public Object getObjectKey(PageState s) {
        BigDecimal id = (BigDecimal) getFormData(s).get(m_id.getName());
        return id;
    }

}
