package LasTres::Races;

use v5.36.0;

use strict;
use warnings;

use feature 'signatures';

use Module::Pluggable search_path => ['LasTres::Race'],
    instantiate => 'new',
    on_require_error => sub ($plugin, $error) {
        die $error;
    };

use Moo;

has hash => (
    is => 'lazy',
);

has hash_playable => (
    is => 'lazy',
);

has hash_all => (
    is => 'lazy',
);

has hash_all_playable => (
    is => 'lazy',
);

sub _build_hash_all($self) {
    my $hash = {};
    my @races = $self->plugins();
    for my $race (@races) {
        $hash->{$race->identifier} = $race;
    }
    return { map { $_ => $self->hash->{$_}->hash } (keys %{$hash}) };
}

sub _build_hash_all_playable($self) {
    my $hash = {};
    my @races = $self->plugins();
    for my $race (@races) {
        $hash->{$race->identifier} = $race;
    }
    for my $race_key (keys %$hash) {
        my $race = $hash->{$race_key}; 
        if (!$race->is_playable) {
            delete $hash->{$race_key};
        }
        $hash->{$race_key} = $race->hash;
    }
    return $hash;
}

sub _build_hash($self) {
    my $hash = {};
    my @races = $self->plugins();
    for my $race (@races) {
        $hash->{$race->identifier} = $race;
    }
    return $hash;
}

sub _build_hash_playable($self) {
    my $hash = {};
    my @races = $self->plugins();
    for my $race (@races) {
        $hash->{$race->identifier} = $race;
    }
    for my $identifier_race (keys %$hash) {
        my $race = $hash->{$identifier_race};
        if (!$race->is_playable) {
            delete $hash->{$identifier_race};
        }
    }
    return $hash;
}

sub get($self, $race_identifier) {
    return $self->hash->{$race_identifier};
}

sub get_playable($self, $race_identifier) {
    my $race = $self->hash->{$race_identifier};
    if (!defined $race) {
        return undef;
    }
    if (!$race->is_playable) {
        return undef;
    }
    return $race;
}
1;
