package EPrints::Plugin::Screen::EPMC::KlarasConnect;

# Package controller: what happens when a librarian presses Enable,
# Disable or Configure for Klaras Connect in Admin > EPrints Bazaar.
#
#   enable    : copy cfg.d (EPrints), create the plugin tables, schedule
#               the indexer job, queue the first health report
#   disable   : remove the indexer job and queued jobs, then remove cfg.d.
#               Data tables stay; the settings screen has "delete data".
#   configure : open the Klaras Connect settings screen

use strict;
use warnings;

use EPrints::Plugin::Screen::EPMC;
our @ISA = ( 'EPrints::Plugin::Screen::EPMC' );

sub new
{
	my( $class, %params ) = @_;
	my $self = $class->SUPER::new( %params );
	push @{ $self->{actions} }, 'configure';
	return $self;
}

sub allow_configure { return shift->can_be_viewed( @_ ) }

sub action_enable
{
	my( $self, $skip_reload ) = @_;
	my $repo = $self->{repository};

	$self->SUPER::action_enable( 1 );

	my $ok = eval {
		require EPrints::KlarasConnect::Schema;
		require EPrints::KlarasConnect::Tick;
		if( EPrints::KlarasConnect::Schema::ensure( $repo ) )
		{
			EPrints::KlarasConnect::Tick::ensure_schedule( $repo );
			EPrints::DataObj::EventQueue->create_unique( $repo, { pluginid => 'Event::KlarasConnect', action => 'health', params => [] } );
		}
		1;
	};
	$repo->log( "klaras_connect: enable steps failed: $@" ) if !$ok;

	$self->{processor}->add_message( 'message', $repo->make_text(
		'Klaras Connect aktif. Minta admin server me-restart Apache, lalu buka Admin > Kesehatan Repositori (Klaras).' ) );

	$self->reload_config if !$skip_reload;
	return 1;
}

sub action_disable
{
	my( $self, $skip_reload ) = @_;
	my $repo = $self->{repository};

	eval {
		require EPrints::KlarasConnect::Schema;
		require EPrints::KlarasConnect::Tick;
		EPrints::KlarasConnect::Tick::remove_schedule( $repo );
		1;
	} or $repo->log( "klaras_connect: disable steps failed: $@" );

	# Admin > EPM > Uninstall stops unless this returns true.
	$self->SUPER::action_disable( $skip_reload );
	return 1;
}

sub action_configure
{
	my( $self ) = @_;
	$self->{processor}->{screenid} = 'Admin::KlarasConnect';
	return 1;
}

1;
