
#                                      Copyright 2024 WebPros International, LLC
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

package Whostmgr::360Monitoring::Agent::Plugins::Roles::Serializable;

use cPstrict;
use Whostmgr::360Monitoring::Util ();
use Types::Serialiser             ();
use Moo::Role;

use experimental qw(builtin);
use builtin      qw(blessed);
use Whostmgr::360Monitoring::Moo;

# That package which tracks roles
use constant ROLE_PACKAGE => do {
    my $pkg = __PACKAGE__;
    $pkg =~ s/::[^:]*?$//;
    $pkg;
};

# A list of roles
use constant ROLES => do {
    my $path = Whostmgr::360Monitoring::Util::class_to_dir(ROLE_PACKAGE);
    opendir( my $dh, $path ) || die "Can't opendir $path $!";
    my @roles =
      map sprintf( "%s::%s", ROLE_PACKAGE, $_ ),
      grep s/.pm$//,
      readdir($dh);
    @roles;
};

sub serialize ($self) {
    my $attrs = Whostmgr::360Monitoring::Util::get_all_attrs($self);

    my %serialize;
    while ( my ( $attr, $options ) = each %$attrs ) {
        my $getter  = "_get_$attr";
        my $default = "_default_$attr";
        if ( defined( my $val_getter = $self->$getter ) ) {
            $serialize{$attr} = $val_getter;
        }
        elsif ( $options->{always_serialize} && defined( my $val_default = $self->$default ) ) {
            $serialize{$attr} = $options->{isa}{coercion}->coerce($val_default);
        }
    }
    \%serialize;
}

1;
__END__

=head1 NAME

Whostmgr::360Monitoring::Agent::Plugins::Roles::Serializable - A Moo::Role to serialize plugin data for output.

=head1 METHODS

=over 8

=item serialize

Returns a hash ref representing the serialized state of the plugin. This is
what is used to generate INI files.

=back
