package LasTres::EventLoop;

use v5.36.0;

use strict;
use warnings;

use feature 'signatures';

use Moo;

has _app => (
    is => 'lazy'
);

has _schema => (
    is => 'lazy'
);

has _redis => (
    is => 'lazy'
);

sub _build__app {
    require LasTres;
    return LasTres->new;
}

sub _build__schema {
    require LasTres::Schema;
    return LasTres::Schema->Schema;
}

sub _build__redis {
    require LasTres::Redis;
    return LasTres::Redis->new;
}

sub _exit_the_program {
    exit 0;
}

$SIG{CHLD} = 'IGNORE';
$SIG{INT} = \&_exit_the_program;
$SIG{QUIT} = \&_exit_the_program;
$SIG{TERM} = \&_exit_the_program;

sub loop($self) {
    my $child_pid = fork;
    if ($child_pid) {
        $self->_real_loop;
    }
}

sub _work_frame($self) {
    my $schema = $self->_schema;
    say 'Starting frame work.';
    sleep int(rand(30));
    say 'Ending frame work.';
}

sub _real_loop($self) {
    my $redis = $self->_redis;
    while (1) {
        if (!defined $redis->db->get($redis->executing_frame_key)) {
            $redis->db->setex($redis->executing_frame_key, 10, 1);
            $self->_work_frame;
        }
        my $ttl =  $redis->db->ttl($redis->executing_frame_key);
        if ($ttl > 0) {
            sleep $ttl;
        }
    }
}
1;
