package Koha::Plugin::Pt::KEEPS::ClearClientCache;

use Modern::Perl;
use DateTime;

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

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEPS - Clear Client Cache',
    author => 'Keep Solutions - joliveira@keep.pt',
    description => 'This plugin will force the cleaning of client-cached files',
    date_authored   => '2024-02-12',
    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 ) = @_;
    my $today = DateTime->today;

    $self->store_data(
    {
    last_modification_date => $today->ymd,
    opac_url_files => '"/opac-tmpl/bootstrap/css/keeps/frontoffice.css",
"/opac-tmpl/bootstrap/css/keeps/frontoffice_21.0507000.css"',
    backoffice_url_files => '"/intranet-tmpl/prog/css/keeps/backoffice.css",
"/intranet-tmpl/prog/css/keeps/backoffice_21.0507000.css"',
    },

    );

    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'};

    unless ($cgi->param('save')) {
        my $lang_dialect = C4::Languages::getlanguage($cgi);

        my $template = $self->get_template({ file => 'configure.tt' });

        $template->param(
            lang_dialect => $lang_dialect,
            opac_url_files => $self->retrieve_data('opac_url_files'),
            backoffice_url_files => $self->retrieve_data('backoffice_url_files'),
            last_modification_date => $self->retrieve_data('last_modification_date'),
            force_the_cache_up_to => $self->retrieve_data('force_the_cache_up_to'),
            last_upgraded   => $self->retrieve_data('last_upgraded'),
        );

        $self->output_html( $template->output() );
    } else {
        $self->store_data(
            {
                opac_url_files => $cgi->param('opac_url_files'),
                backoffice_url_files => $cgi->param('backoffice_url_files'),
                last_modification_date => $cgi->param('last_modification_date'),
                force_the_cache_up_to => $cgi->param('force_the_cache_up_to'),
                last_configured_by => C4::Context->userenv->{'number'},
            }
        );
        $self->go_home();
    }
}

sub intranet_js {
    my ($self) = @_;
    return $self->generate_js();
}

sub opac_js {
    my ($self) = @_;
    return $self->generate_js();
}

sub generate_js {
    my ($self) = @_;
    my $opac_url_files         = $self->retrieve_data('opac_url_files') || 0;
    my $backoffice_url_files         = $self->retrieve_data('backoffice_url_files') || 0;
    my $last_modification_date = $self->retrieve_data('last_modification_date') || 0;
    my $force_the_cache_up_to = $self->retrieve_data('force_the_cache_up_to') || 0;

    return qq%
<script>
    var pathname = window.location.pathname;
    var opac_url_files = [$opac_url_files];
    var backoffice_url_files = [$backoffice_url_files];
    var last_modification_date = "$last_modification_date";
    var force_the_cache_up_to = "$force_the_cache_up_to";
    console.log("cache checking");
    
    function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
    }

    function setCookie(name, value) {
        document.cookie = name + "=" + value + "; path=/";
    }

    var forceCacheDate = new Date(force_the_cache_up_to).toISOString().split('T')[0];
    var currentDate = new Date().toISOString().split('T')[0];

    if (forceCacheDate >= currentDate && forceCacheDate != "2000-01-01" ) {
        setCookie("CacheFilesDate", "1970-01-01");    
    }

    var CacheFilesDate = getCookie("CacheFilesDate");
    if (!CacheFilesDate) {
        CacheFilesDate = "1970-01-01";
        setCookie("CacheFilesDate", CacheFilesDate);
    }

    if (last_modification_date > CacheFilesDate) {
        setCookie("CacheFilesDate", last_modification_date);

        var isBackofficeCss = 0;
        if (\$('link[href^="/intranet-tmpl/prog/css/keeps/backoffice_"]').length > 0) {
            isBackofficeCss = 1;
        }

        var url_files = isBackofficeCss ? backoffice_url_files : opac_url_files;

        for (var i = 0; i < url_files.length; i++) {
            var url = url_files[i];
            var extension = url.split('.').pop().toLowerCase();

            if (extension === 'css') {
                var linkElement = document.createElement("link");
                linkElement.href = url + "?" + last_modification_date + Math.random().toString(36).substring(2, 10);;
                linkElement.rel = "stylesheet";
                linkElement.type = "text/css";
                document.head.appendChild(linkElement);

                console.log("Style inserted:", url);
            } else if (extension === 'js') {
                var scriptElement = document.createElement("script");
                scriptElement.src = url + "?" + last_modification_date + Math.random().toString(36).substring(2, 10);;
                scriptElement.type = "text/javascript";
                document.body.appendChild(scriptElement);

                console.log("Script inserted:", url);
            } else {
                console.warn("Unsupported file type:", url);
            }
        }
    }

</script>
%;
}





1;
