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

import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.factories.annotations.Start;


/**
 * Factory to create LockStragtegy instance.
 *
 * @author Ben Wang
 */
@NonVolatile
public class LockStrategyFactory
{

   /**
    * Transaction locking isolation level. Default.
    */
   private IsolationLevel lockingLevel = IsolationLevel.REPEATABLE_READ;
   private Configuration configuration;

   @Inject
   public void injectDependencies(Configuration configuration)
   {
      this.configuration = configuration;
   }

   @Start(priority = 1)
   public void start()
   {
      lockingLevel = configuration.isNodeLockingOptimistic() ? IsolationLevel.REPEATABLE_READ : configuration.getIsolationLevel();
   }

   public LockStrategy getLockStrategy()
   {
      return getLockStrategy(lockingLevel);
   }

   public LockStrategy getLockStrategy(IsolationLevel lockingLevel)
   {
      //if(log_.isTraceEnabled()) {
      // log_.trace("LockStrategy is: " + lockingLevel);
      //}
      if (lockingLevel == null)
         return new LockStrategyNone();
      switch (lockingLevel)
      {
         case NONE:
            return new LockStrategyNone();
         case SERIALIZABLE:
            return new LockStrategySerializable();
         case READ_UNCOMMITTED:
            return new LockStrategyReadUncommitted();
         case READ_COMMITTED:
            return new LockStrategyReadCommitted();
         case REPEATABLE_READ:
         default:
            return new LockStrategyRepeatableRead();
      }
   }

   public void setIsolationLevel(IsolationLevel level)
   {
      lockingLevel = level;
   }
}
