use strict;
use warnings;

use lib 't/lib';
use TestHelper;
use Test::More;

use Async::Event::Interval;

my $mod = 'Async::Event::Interval';

{
    my $one = $mod->new(0, sub {});
    my $two = $mod->new(0, sub {});

    my $events = Async::Event::Interval::events();

    is ref $events, 'HASH', 'Class events() returns a hash ref ok';

    is keys %$events, 2, "Two events have been created ok";

    for (keys %$events) {
        like $_, qr/^\w+$/, "Events key $_ is a word ok";
        is ref $events->{$_}, 'HASH', "Event $_ is a hash ref ok";
        is keys %{ $events->{$_} }, 3, "After creation, event $_ hash has error/waiting plus interval";
    }

    $one->start;
    $two->start;

    select(undef, undef, undef, 0.2);

    $events = Async::Event::Interval::events();

    for (keys %$events) {
        like $_, qr/^\d+$/, "Events key $_ is still an integer ok";
        is $events->{$_}{runs} > 0, 1, "Event $_ has a 'runs' key set ok";
        is ref $events->{$_}, 'HASH', "Event $_ is still a hash ref ok";
        is keys %{ $events->{$_} }, 5, "After creation, event $_ hash has 5 keys";
        like $events->{$_}{pid}, qr/^\d+$/, "Event $_ has pid key with a proper PID";
        like $events->{$_}{interval}, qr/^(\d+\.)?\d+$/, "Event $_ has interval key with a proper interval";
    }

    my $a = $one->shared_scalar;
    my $b = $two->shared_scalar;
    my $aa = $one->shared_scalar;
    my $bb = $two->shared_scalar;

    $events = Async::Event::Interval::events();

    for (keys %$events) {
        like $_, qr/^\d+$/, "Events key $_ is still an integer ok";
        is ref $events->{$_}, 'HASH', "Event $_ is still a hash ref ok";
        is keys %{ $events->{$_} }, 6, "After creation, event $_ hash has proper number of keys ok";
        like $events->{$_}{pid}, qr/^\d+$/, "Event $_ has pid key with a proper PID";
        is ref $events->{$_}{shared_scalars}, 'ARRAY', "Event $_ has shared_scalars arrayref";
        is scalar @{ $events->{$_}{shared_scalars} }, 2, "Event $_ has two shared scalars";
        is $events->{$_}{runs} > 0, 1, "Event $_ has a 'runs' key set ok";
        like $events->{$_}{interval}, qr/^(\d+\.)?\d+$/, "Event $_ has interval key with a proper interval";

        for my $shared_key (@{ $events->{$_}{shared_scalars} }) {
            like $shared_key, qr/^0x[a-f0-9]+$/, "Shared scalar key $shared_key is a hex string with 0x prefix";
        }
    }

    my $id = 0;

    for ($one, $two) {
        is $_->info()->{pid}, $events->{$id}{pid}, "info() pid matches for event $id";

        like $_->info()->{interval}, qr/^(\d+\.)?\d+$/, "info() has interval key with a proper interval for event $id";
        for my $shared_key (@{$_->info->{shared_scalars}}) {
            like $shared_key, qr/^0x[a-f0-9]+$/, "Shared scalar key $shared_key is a hex string with 0x prefix";
        }

        my $actual_id = $_->id;

        is $actual_id, $id, "Event $actual_id has proper id()";

        $id++;
    }
}