package Koha::Plugin::Pt::KEEPS::BiblioReindex;

use Modern::Perl;

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

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEPS - Biblio Reindex',
    author => 'Keep Solutions',
    description => 'Allows to reindex a single biblio',
    date_authored   => '2022-01-24',
    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 intranet_js {
    my ( $self ) = @_;

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

    return qq%
<script>
    var pathname = window.location.pathname;
    var searchString = window.location.search;

    if (pathname.match("/catalogue/detail.pl") && searchString.match("biblionumber=")) {
        var biblio_reindex_plugin_path = "$path";

        var lang = \$('html').attr('lang');
        if (lang == null) {
            lang = \$('html').attr('xml:lang');
        }

        // Set the global configs to synchronous 
        \$.ajaxSetup({
            async: false
        });

        var BIB_REINDEX_TOKENS = {};
        \$.getJSON(biblio_reindex_plugin_path + `/i18n/\${lang}.json`, function (data) {
            BIB_REINDEX_TOKENS = data;
        }).fail(function() { 
            \$.getJSON(biblio_reindex_plugin_path + `/i18n/default.json`, function (data) {
                BIB_REINDEX_TOKENS = data;
            }); 
        });

        \$.ajaxSetup({
            async: true
        });


        var urlParams = new URLSearchParams(searchString);
        var biblionumber = urlParams.get('biblionumber');
 
        \$('#placehold').parent().after(`
            <div class="btn-group">
                <a id="reindexbiblio" class="btn btn-default">
                    <i class="fa fa-refresh"></i>
                    \${BIB_REINDEX_TOKENS.reindexButton}
                </a>
            </div>
        `);
        
        \$('#reindexbiblio').on('click', function () {
            \$.ajax({
                url: biblio_reindex_plugin_path + `/biblio-reindex.pl?biblionumber=` + biblionumber,
                type: "GET",
                success: function (data, textStatus, request) {
                    alert(`\${BIB_REINDEX_TOKENS.reindexSuccess}`);
                    location.reload();
                },
                error: function (response, textStatus, errorThrown) {
                    alert(`\${BIB_REINDEX_TOKENS.reindexError}`);
                }
            });
        });
	}
</script>
%;
}

1;