package Cpanel::Plugins::Components::360::BaseWidget;

use feature 'state';
use Moo;
use cPstrict;

use Cpanel::Imports;

extends 'Cpanel::Plugins::Components::Base';
with 'Cpanel::Plugins::Components::Role::Template';

has '+slot' => (
    default => 'page-bottom',
);

has '+process' => (
    default => 1,
);

# Only show the widget for Whm root user and if 360 is setup and running
around 'is_enabled' => sub ( $orig, @args ) {

    # If we have an API key, we can show the widget
    return get_api_key() ? 1 : 0;
};

=head2 get_api_key()

Fetch the current users api_key if it exists. 

=head3 RETURNS

String - The API key for Server Monitoring, or an empty string if not set.

=cut

sub get_api_key {
    my $credentials = get_credentials();
    return $credentials && $credentials->{api_key} // '';
}

=head2 get_credentials()

Fetch the current users credentials for Server Monitoring. The credentials are cached so 
after the first call, subsequent calls will return the cached value.

=head3 RETURNS

HashRef - The credentials hash containing the API key and other details, or undefined if not set.

Some elements of the hash may be missing or may be undefined if not set yet.

=cut

sub get_credentials {
    state $credentials;
    if ( !$credentials ) {
        require Whostmgr::360Monitoring::Setup;
        $credentials = Whostmgr::360Monitoring::Setup::get_credentials();
    }
    return $credentials;
}

1;
