package LasTres;

use v5.36.0;

use strict;
use warnings;

use Mojo::Base 'Mojolicious', -signatures;

# This method will run once at server start
sub startup ($self) {

    # Load configuration from config file
    my $config = $self->plugin('NotYAMLConfig');

    # Configure the application
    $self->secrets( $config->{secrets} );

    # Router
    my $r = $self->routes;

    $self->helper(user => sub($self) {
        require LasTres::DAO::Players;
        my $result_set_players = LasTres::DAO::Players->ResultSet;
        my $uuid = $self->session->{uuid};
        if (!defined $uuid) {
            return;
        }
        my @players = $result_set_players->search({
            uuid => $uuid,
        });
        my $player = $players[0];
        if (!defined $player) {
            delete $self->session->{uuid};
            return;
        }
        return $player;
    });

    my $sessions = Mojolicious::Sessions->new;
    $sessions->cookie_name('LasTres');
    $sessions->default_expiration(0);

    # Normal route to controller
    $r->get('/')->to('Root#index');
    $r->get('/races/playable')->to('Race#playable');
    $r->get('/my/pjs')->to('PJ#list_my_pjs');

    $r->post('/player/register')->to('Player#register');
    $r->post('/player/login')->to('Player#login');
    $r->post('/player/check_login')->to('Player#check_login');
    $r->post('/pj/create')->to('PJ#create');;
    $r->websocket('/ws')->to('Websocket#ws');
    $self->hook(before_server_start => sub ($server, $self) {
        require LasTres::EventLoop;
        LasTres::EventLoop->new->loop;
    });
}

1;
