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

import com.arsdigita.bebop.FormData;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.cms.Folder;
import com.arsdigita.cms.ItemSelectionModel;
import com.arsdigita.db.Sequences;
import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.persistence.OID;
import com.arsdigita.persistence.SessionManager;
import org.apache.log4j.Logger;

import java.math.BigDecimal;

public class FolderCreator extends FolderForm {

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

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


    public FolderCreator(String name, FolderSelectionModel parent) {
        super(name, parent);
    }

    public void init(FormSectionEvent e) throws FormProcessException {
        PageState state = e.getPageState();
        ItemSelectionModel m = getItemSelectionModel();

        // Create a new item_id and set it as the key
        try {
            m.setSelectedKey(state, Sequences.getNextValue());
        } catch (java.sql.SQLException ex) {
            s_log.error("Error retrieving sequence.nextval", ex);
            throw new FormProcessException(ex.getMessage());
        }
    }


    public void process(FormSectionEvent e) throws FormProcessException {
        PageState s = e.getPageState();
        FormData data = e.getFormData();
        ItemSelectionModel m = getItemSelectionModel();
        BigDecimal id =  (BigDecimal) m.getSelectedKey(s);
        Folder parent = getCurrentFolder(s);

        Folder child = null;
        try {
            child = new Folder(id);
        } catch (DataObjectNotFoundException ex) {
            child = new Folder(SessionManager.getSession().create
                               (new OID(Folder.BASE_DATA_OBJECT_TYPE, id)));
        }

        updateFolder(child, parent, (String)data.get(NAME), (String)data.get(TITLE));
    }
}
