# Copyright (C) Innuos
# SPDX-License-Identifier: GPL-2.0

package Plugins::PluginManagerAPI::Controllers::Server;

use warnings;
use strict;

use Slim::Utils::Log;
use Slim::Utils::PluginManager;
use Slim::Utils::PluginDownloader;
use Slim::Utils::Timers;


use Data::Dumper;
use JSON::XS::VersionOneAndTwo;
use Scalar::Util qw(blessed);

use Plugins::PluginManagerAPI::Utilities;


my $log = logger('plugin.PluginManagerAPI');


sub pendingStatus {
	my ($action, $input, $callback) = @_;
	main::DEBUGLOG && $log->is_debug && $log->debug('pendingStatus++');

	my $response = {
		'requiresRestart' => JSON::XS::false,		
	};
	
	if (my $restart = Slim::Utils::PluginManager->needsRestart()) {
		main::DEBUGLOG && $log->is_debug && $log->debug('restart status : ' . $restart);
			

		$response->{'requiresRestart'} = JSON::XS::true;


	}

	my $json = Plugins::PluginManagerAPI::Utilities::encodeReturnJSON($response);	
	$callback->(Plugins::PluginManagerAPI::Utilities::HTTP_OK, $json);

	main::DEBUGLOG && $log->is_debug && $log->debug('pendingStatus--');
	return;

}

sub restart {
	my ($action, $input, $callback) = @_;	
	main::DEBUGLOG && $log->is_debug && $log->debug('restart++');

	if ( main::canRestartServer() ) {
		
		Slim::Utils::Timers::setTimer(undef, Time::HiRes::time() + 2, \&_restartServer);
		$callback->(Plugins::PluginManagerAPI::Utilities::HTTP_OK, Plugins::PluginManagerAPI::Utilities::encodeSuccessJSON('ok'));

	} else {

		Plugins::PluginManagerAPI::Utilities::callbackError( $callback, "Server currently not in a state to be able to be restarted", Plugins::PluginManagerAPI::Utilities::HTTP_PRECONDITION_FAILED);	 
	}

	main::DEBUGLOG && $log->is_debug && $log->debug('restart--');
	return;
}

sub _restartServer {

	if (Slim::Utils::PluginDownloader->downloading) {

		Slim::Utils::Timers::setTimer(undef, Time::HiRes::time() + 2, \&_restartServer);

	} else {

		main::restartServer();
	}
}


1;
