#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 14;

use lib qw( ./t ./lib );

use PS::IPP::IData::Server;
use PS::IPP::IData::Util qw( :standard );
use Test::IData;

my $idata = "PS::IPP::IData::Server";

$idata->setup(
    "DBI:mysql:database=test:host=localhost",
    "test",
    "",
);

Test::IData->setup;

{
    $idata->create_object( "foo" );

    $idata->lock_object( "foo", "read" );

    ok( $idata->unlock_object( "foo", "read" ), "read unlock" );
}

Test::IData->setup;

{
    $idata->create_object( "foo" );

    $idata->lock_object( "foo", "read" );
    $idata->lock_object( "foo", "read" );

    ok( $idata->unlock_object( "foo", "read" ), "read unlock" );
    ok( $idata->unlock_object( "foo", "read" ), "read unlock" );
}

Test::IData->setup;

{
    $idata->create_object( "foo" );

    $idata->lock_object( "foo", "write" );

    ok( $idata->unlock_object( "foo", "write" ), "write unlock" );
}

Test::IData->setup;

eval {
    $idata->unlock_object( "foo", "read" );
};
like( $@, qr/storage object does not exist/, "storage object does not exist" );

Test::IData->setup;

eval {
    $idata->unlock_object( "foo", "write" );
};
like( $@, qr/storage object does not exist/, "storage object does not exist" );

Test::IData->setup;

eval {
    $idata->create_object( "foo" );

    $idata->unlock_object( "foo", "read" );
};
like( $@, qr/can not remove non-existant read lock/, "no lock set" );

Test::IData->setup;

eval {
    $idata->create_object( "foo" );

    $idata->unlock_object( "foo", "write" );
};
like( $@, qr/can not remove non-existant write lock/, "no lock set" );

Test::IData->setup;

eval {
    $idata->create_object( "foo" );
    $idata->lock_object( "foo", "write" );

    $idata->unlock_object( "foo", "read" );
};
like( $@, qr/can not have a read lock under a write lock/, "read unlock under write lock" );

Test::IData->setup;

eval {
    $idata->create_object( "foo" );
    $idata->lock_object( "foo", "read" );

    $idata->unlock_object( "foo", "write" );
};
like( $@, qr/can not have a write lock under a read lock/, "write unlock under read lock" );

Test::IData->setup;

eval {
    $idata->unlock_object();
};
like( $@, qr/2 were expected/, "no params" );

Test::IData->setup;

eval {
    $idata->unlock_object( "foo" );
};
like( $@, qr/2 were expected/, "not enough params" );

Test::IData->setup;

eval {
    $idata->unlock_object( "foo", "both" );
};
like( $@, qr/is read or write/, "not read or write" );

Test::IData->setup;

eval {
    $idata->unlock_object( "foo", 'read', 3 );
};
like( $@, qr/2 were expected/, "too many params" );

Test::IData->cleanup;
