/* BdfServer_DirectoryStorage - Copyright (c) 2009-2022 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.storage.directory.implementations;

import fr.exemole.bdfserver.api.storage.StorageRoot;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.mapeadores.util.text.RelativePath;


/**
 *
 * @author Vincent Calame
 */
public class StorageRootImpl implements StorageRoot {

    private final Map<String, Lock> lockMap = new HashMap<String, Lock>();
    private final File rootDirectory;

    public StorageRootImpl(File rootDirectory) {
        this.rootDirectory = rootDirectory;
    }

    @Override
    public File getFile(RelativePath filePath) {
        if (filePath.isEmpty()) {
            return rootDirectory;
        }
        return new File(rootDirectory, filePath.getPath());
    }

    @Override
    public Lock getLock(RelativePath filePath) {
        Lock lock = lockMap.get(filePath.getPath());
        if (lock == null) {
            return getOrCreateLock(filePath);
        } else {
            return lock;
        }
    }

    private synchronized Lock getOrCreateLock(RelativePath filePath) {
        String path = filePath.getPath();
        Lock lock = lockMap.get(path);
        if (lock == null) {
            lock = new InternalLock();
            lockMap.put(path, lock);
        }
        return lock;
    }


    private static class InternalLock implements Lock {

        private InternalLock() {

        }

    }

}
