package com.atlassian.stash.internal.concurrent;

import com.atlassian.beehive.ClusterLockService;
import com.atlassian.bitbucket.concurrent.RepositoryLock;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.util.Operation;

import javax.annotation.Nonnull;

import static com.google.common.base.Preconditions.checkNotNull;

public class ClusterRepositoryLock implements RepositoryLock {

    private static final String LOCK_PREFIX = "lock.bbs.repo.";

    private final ClusterMappedLock lock;

    public ClusterRepositoryLock(ClusterLockService clusterLockService, String lockName) {
        lock = new ClusterMappedLock(clusterLockService, LOCK_PREFIX + lockName);
    }

    @Override
    public <T, E extends Exception> T withLock(int repositoryId, @Nonnull Operation<T, E> operation) throws E {
        return lock.withLock(Integer.toString(repositoryId), operation);
    }

    @Override
    public <T, E extends Exception> T withLock(@Nonnull Repository repository, @Nonnull Operation<T, E> operation) throws E {
        return lock.withLock(Integer.toString(checkNotNull(repository, "repository").getId()), operation);
    }
}
