package Koha::Plugin::Pt::KEEPS::KEEPSPlugin;

use Modern::Perl;

use base qw(Koha::Plugins::Base);

use Koha::Plugins;
use DBI;
use Encode;
use JSON;
use Data::Dumper;

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEPS - KEEPS Plugin',
    author => 'Keep Solutions',
    description => 'Summarizes the plugins installed in this Koha instance',
    date_authored   => '2022-02-09',
    date_updated    => undef,
    minimum_version => '21.05',
    maximum_version => undef,
    version         => $VERSION,
};

sub new {
    my ( $class, $args ) = @_;

    $args->{'metadata'} = $metadata;
    $args->{'metadata'}->{'class'} = $class;

    my $self = $class->SUPER::new($args);

    return $self;
}

# Mandatory even if does nothing
sub install {
    my ( $self, $args ) = @_;

    return 1;
}

# Mandatory even if does nothing
sub upgrade {
    my ( $self, $args ) = @_;

    return 1;
}

# Mandatory even if does nothing
sub uninstall {
    my ( $self, $args ) = @_;

    return 1;
}

sub configure {
    my ($self, $args) = @_;
    my $cgi = $self->{'cgi'};

    my $lang_dialect = C4::Languages::getlanguage($cgi);

    my $template = $self->get_template({ file => 'configure.tt' });
    my $client_name = C4::Context->preference("LibraryName");
    my $koha_name = C4::Context->config("koha_name");
    my $opac_url = C4::Context->preference('OPACBaseURL');
    my $intranet_url = C4::Context->preference('staffClientBaseURL');
    my @plugin_info = ();

    my @plugins = Koha::Plugins->new()->GetPlugins(
        {
            all    => 1,
            errors => 1
        }
    );

    foreach my $plugin_data ( @plugins ) {
        my %hash;
        $hash{name} = $plugin_data->{metadata}->{name};
        $hash{version} = $plugin_data->{metadata}->{version};
        $hash{class} = $plugin_data->{metadata}->{class};
        $hash{author} = $plugin_data->{metadata}->{author};
        $hash{description} = $plugin_data->{metadata}->{description};
        $hash{date_authored} = $plugin_data->{metadata}->{date_authored};
        $hash{date_updated} = $plugin_data->{metadata}->{date_updated};
        $hash{minimum_version} = $plugin_data->{metadata}->{minimum_version};
        $hash{maximum_version} = $plugin_data->{metadata}->{maximum_version};
        $hash{is_enabled} = $plugin_data->is_enabled();
        push @plugin_info, \%hash;
    }
    local $Data::Dumper::Terse = 1;

    my %json_hash = ( client => $koha_name, name => $client_name, opac_url => $opac_url, intranet_url => $intranet_url, plugins => \@plugin_info );
    my $json = encode_json \%json_hash;

    $template->param(
        lang_dialect => $lang_dialect,
        plugin_json          => $json
    );

    $self->output_html( $template->output() );
}

sub opac_js {
    my ( $self ) = @_;

    my $path = $self->get_plugin_http_path();

    return qq%
<script>
    var pathname = window.location.pathname;
    var keeps_plugin_path = "$path";

</script>
%;
}

1;