/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.myfaces.orchestra.conversation;

import org.apache.myfaces.orchestra.conversation.model.UserData;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * A backing bean for a view (ie a "view controller") that has an associated
 * persistence context.
 * <p>
 * In real applications, the PersistenceContext is more likely to be on a
 * DAO bean referenced from the backing bean than directly on the backing
 * bean class. However that doesn't change the principles.
 */
public class PersistentBackingBean implements ConversationBindingListener
{
    /**
     * Inject a PersistenceContext that is associated with the conversation
     * that this bean instance is in.
     */
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * A UserData instance read via the PersistenceContext object associated
     * with this bean, ie one associated with the conversation that this bean
     * is in.
     */
    private UserData restartedUser;

    private UserData createdUser;

    public PersistentBackingBean()
    {
    }

    public void valueBound(ConversationBindingEvent event)
    {
    }

    public void valueUnbound(ConversationBindingEvent event)
    {
    }

    public UserData getRestartedUser()
    {
        return restartedUser;
    }

    /**
     * Create a UserData object and commit it to the database.
     * <p>
     * Because this method is marked with the Transactional annotation, a
     * commit will be performed when the method returns successfully
     * (without exception), and a rollback will be performed when the
     * method throws an exception.
     */
    @Transactional
    public UserData createUser()
    {
        // Create an object that is not yet attached to a persistence context.
        UserData userData = new UserData();
        userData.setUsername("test");

        // Attach the object to the persistence context. Note that nothing
        // is written to the database at this point; that only happens when
        // the persistence context is flushed and committed. Due to the
        // Transactional annotation on this method, that happens when this
        // method returns.
        entityManager.persist(userData);

        createdUser = userData;

        return userData;
    }

    public UserData readUser(Long id)
    {
        return entityManager.find(UserData.class, id);
    }

    /**
     * Invalidate the conversation in which this bean lives. 
     * <p>
     * This means that the next attempt to dereference a proxy or
     * EL expression will cause a new instance of this bean to
     * be created. A new Conversation instance will be created to
     * hold that bean, and a new PersistenceContext object will
     * also be created (and then injected into this instance).
     */
    public void invalidateConversation()
    {
        Conversation.getCurrentInstance().invalidate();
    }

    /**
     * Invalidate the conversation in which this bean lives, and
     * then create a new bean instance (in a new conversation) and
     * copy some data from the old to the new instance.
     * <p>
     * Using invalidateAndRestart allows information to be communicated
     * between one instance of this bean and its replacement.
     */
    public void invalidateAndRestartConversation()
    {
        PersistentBackingBean conv = (PersistentBackingBean) 
            ConversationUtils.invalidateAndRestartCurrent();
        conv.setRestartedUser(createdUser.getId());
    }

    public void setRestartedUser(Long id)
    {
        restartedUser = readUser(id);
    }

    public void updateUser(Long id, String username)
    {
        UserData user = readUser(id);
        user.setUsername(username);
    }
}
