package de.duehl.basics.io.lock;

import static org.junit.Assert.*;

import java.io.File;
import java.net.URL;

import org.junit.Test;

import de.duehl.basics.io.FileHelper;
import de.duehl.basics.io.exceptions.IORuntimeException;

public class MultipleStartLockTest {

    private final String path;

    private String path() {
        String className = getClass().getName();
        int dotIndex = className.indexOf(".");
        while (dotIndex > -1) {
            className = className.substring(dotIndex + 1); // endet nicht auf .
            dotIndex = className.indexOf(".");
        }

        URL url = getClass().getResource(className + ".class");
        File f = new File(url.getPath());
        int numberOfSubfolders = 7;
        for (int i=0; i<numberOfSubfolders; ++i) {
            f = new File(f.getParent());
        }
        String p = f.getPath() + File.separator + "data" + File.separator
                + "lock" + File.separator;
        return p;
    }

    public MultipleStartLockTest() {
        path = path();
    }


    /* -------------------------- TESTS -------------------------- */


    @Test(expected = IORuntimeException.class)
    public void tryToCreateLockInNotExistingDirectory() {
        String lockFilename = FileHelper.concatPathesMultiple(path, "notExistingSubdir", ".lock");
        MultipleStartLock lock = new MultipleStartLock(lockFilename);
        lock.lock();
    }

    @Test
    public void tryToCreateLockButItExists() {
        String lockFilename = FileHelper.concatPathes(path, ".lock");
        FileHelper.createEmptyFile(lockFilename);

        MultipleStartLock lock = new MultipleStartLock(lockFilename);
        boolean lockGained = lock.lock();
        assertFalse(lockGained);

        FileHelper.deleteFile(lockFilename);
    }

    @Test
    public void createLockAndRemove() {
        String lockFilename = FileHelper.concatPathes(path, ".lock");

        MultipleStartLock lock = new MultipleStartLock(lockFilename);
        boolean lockGained = lock.lock();
        assertTrue(lockGained);

        lock.unlock();
    }

}
