/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.aspects.versioned;

import org.jboss.aop.Advised;
import org.jboss.aop.proxy.ClassProxy;
import org.jboss.aop.proxy.ClassProxyFactory;
import org.jboss.aop.util.PayloadKey;

/**
 *  This interceptor handles chooses an object to invoke
 *  on based on the transaction
 *
 *  @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 *  @version $Revision: 1.2.2.3 $
 */
public class Versioned
{
   public static final String VERSIONED = "VERSIONED";
   public static final String VERSIONED_OBJECT = "VERSIONED_OBJECT";
   public static final String READONLY = "read-only";

   public static Object makeVersioned(Object target)
      throws Exception
   {
      if (target instanceof ClassProxy) throw new IllegalStateException("A ClassProxy is not allowed to be Versioned.  You must have a concrete object");
      ClassProxy proxy = ClassProxyFactory.newInstance(target.getClass());
      VersionedObject versioned = new VersionedObject(target);
      proxy._getInstanceAdvisor().getMetaData().addMetaData(VERSIONED, VERSIONED_OBJECT, versioned, PayloadKey.TRANSIENT);
      proxy._getInstanceAdvisor().appendInterceptor(VersionedObjectInterceptorFactory.getInstance());
      proxy._getInstanceAdvisor().appendInterceptor(new VersionedObjectForwardingInterceptor());
      return proxy;
   }

   static DistributedVersionManager localManager = null;
   public static synchronized DistributedVersionManager getLocalVersionManager() throws Exception
   {
      if (localManager == null)
      {
         LocalSynchronizationManager synchManager = new LocalSynchronizationManager(null);
         localManager = new DistributedVersionManager(1000, synchManager);
         synchManager.versionManager = localManager;
         
      }
      return localManager;
   }

   public static void makePerFieldVersioned(Object target) throws Exception
   {
      if (!(target instanceof Advised)) throw new IllegalArgumentException("Cannot do per field versioning with a non-Advised object");
      Advised advised = (Advised)target;
      getLocalVersionManager().makeVersioned(advised);
   }
   
}
