package de.duehl.basics.io.lock;

/*
 * Copyright 2017 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import de.duehl.basics.io.FileHelper;

public class WaitingFileLockTest {

    /** Anzahl der Sekunden, die darauf gewartet wird, den Lock zu erhalten. */
    private static final int WAIT_FOR_LOCK_SECONDS = 1;

    /** Anzahl der Millisekunden, die nach einem nicht erhaltenen Lock gewartet wird. */
    private static final int SLEEP_BEFORE_RETRY_MILLISECONDS = 10;

    private static String LOCK_FILE = "c:\\temp\\WaitingFileLockTest.lock";

    @Before
    public void removeTestFile() {
        FileHelper.deleteFileIfExistent(LOCK_FILE);
    }

    @Test
    public void createObject() {
        WaitingFileLock lock = new WaitingFileLock(WAIT_FOR_LOCK_SECONDS,
                SLEEP_BEFORE_RETRY_MILLISECONDS, LOCK_FILE);
        assertNotNull(lock);
    }

    @Test
    public void createLockWithSuccess() {
        WaitingFileLock lock = new WaitingFileLock(WAIT_FOR_LOCK_SECONDS,
                SLEEP_BEFORE_RETRY_MILLISECONDS, LOCK_FILE);
        boolean success = lock.lock();
        assertTrue(success);
    }

    @Test
    public void createTwoTimesLockWithoutSuccess() {
        WaitingFileLock lock = new WaitingFileLock(WAIT_FOR_LOCK_SECONDS,
                SLEEP_BEFORE_RETRY_MILLISECONDS, LOCK_FILE);
        boolean success = lock.lock();
        assertTrue(success);
        success = lock.lock();
        assertFalse(success);
        success = lock.unlock();
        assertTrue(success);
    }

    @Test
    public void createAndReleaseLockWithSuccess() {
        WaitingFileLock lock = new WaitingFileLock(WAIT_FOR_LOCK_SECONDS,
                SLEEP_BEFORE_RETRY_MILLISECONDS, LOCK_FILE);
        boolean success = lock.lock();
        assertTrue(success);
        success = lock.unlock();
        assertTrue(success);
    }

    @Test
    public void releaseLockWithoutCreationWithoutSuccess() {
        WaitingFileLock lock = new WaitingFileLock(WAIT_FOR_LOCK_SECONDS,
                SLEEP_BEFORE_RETRY_MILLISECONDS, LOCK_FILE);
        boolean success = lock.unlock();
        assertFalse(success);
    }

    @Test
    public void twoTimesCreateAndReleaseLockWithSuccess() {
        WaitingFileLock lock = new WaitingFileLock(WAIT_FOR_LOCK_SECONDS,
                SLEEP_BEFORE_RETRY_MILLISECONDS, LOCK_FILE);
        boolean success = lock.lock();
        assertTrue(success);
        success = lock.unlock();
        assertTrue(success);

        success = lock.lock();
        assertTrue(success);
        success = lock.unlock();
        assertTrue(success);
    }

}
