package Koha::Plugin::Pt::KEEPS::QRCode;

use Modern::Perl;

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

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEPS - OPAC QR Code',
    author => 'Keep Solutions',
    description => 'Adds QR codes to OPAC results and detail pages',
    date_authored   => '2022-01-27',
    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 opac_js {
    my ( $self ) = @_;

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

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

    \$(document).ready(function () {
        if (pathname.match("opac-detail.pl") || pathname.match("opac-search.pl")) {

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

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

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

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

            try {
                \$.getScript(qr_code_plugin_path + '/qrcode.js', function() {
                    
                    var qr = qrcode(10, "M");
                    qr.addData(window.location.href);
                    qr.make();

                    \$("#facetcontainer").append('<h5 style="font-size: 80\%">' + qr_code_TOKENS.results_qr + '</h5>');
                    \$("#ulactioncontainer").append('<h5 style="font-size: 80\%; margin-left: 35px">' + qr_code_TOKENS.record_qr + '</h5>');

                    \$("#facetcontainer").append('<div>' + qr.createImgTag() + '</div>');
                    \$("#ulactioncontainer").append('<div style="margin-left: 35px">' + qr.createImgTag() + '</div>');

                });
            } catch (e) {
                alert(e);
            }
        }
    });

</script>
%;
}

1;