/*
 * This file is part of the Vamsas Client version 0.2. 
 * Copyright 2010 by Jim Procter, Iain Milne, Pierre Marguerite, 
 *  Andrew Waterhouse and Dominik Lindner.
 * 
 * Earlier versions have also been incorporated into Jalview version 2.4 
 * since 2008, and TOPALi version 2 since 2007.
 * 
 * The Vamsas Client is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *  
 * The Vamsas Client is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with the Vamsas Client.  If not, see <http://www.gnu.org/licenses/>.
 */
package uk.ac.vamsas.client.simpleclient;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LockFactory {
  protected static Log log = LogFactory.getLog(LockFactory.class);

  public static int locktype = 0; // use file lock by default

  public static String[] locktypes = { "file", "native" };
  {
    String lockt = System.getProperty("vamsas.locktype");
    if (lockt != null) {
      int i, j;
      for (i = 0, j = locktypes.length; i < j
          && locktypes[i].equalsIgnoreCase(lockt); i++)
        ;
      if (i >= j) {
        String lt = "'" + locktypes[0] + "'";
        for (i = 1; i < j; i++)
          lt += ",'" + locktypes[i] + "'";
        log.warn("System property vamsas.locktype takes one of " + lt);
        log.warn("Defaulting to Locktype of " + locktypes[locktype]);
      }
    } else
      log.debug("Defaulting to Locktype of " + locktypes[locktype]);
  }

  /**
   * lock target (blocks until lock is obtained)
   * 
   * @param target
   * @return lock
   */
  public static Lock getLock(java.io.File target) {
    return getLock(target, true);
  }

  public static Lock getLock(java.io.File target, boolean block) {
    if (locktype == 0)
      return new FileLock(target, block);
    if (locktype == 1)
      return new NativeLock(target, block);
    log.fatal("Implementation Error! No valid Locktype value");
    return null;
  }

  /**
   * try to lock target
   * 
   * @param target
   * @return null if lock was not possible
   */
  public static Lock tryLock(File target) {
    return getLock(target, false);
  }
}
