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

package Plugins::PluginManagerAPI::Utilities;


use warnings;
use strict;

use JSON::XS::VersionOneAndTwo;

use Slim::Utils::Log;
use Slim::Control::Request;

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

# HTTP Response Codes .  Only the ones we need rather than import the whole of HTTP::Status
use constant HTTP_OK                    => 200;
use constant HTTP_BAD_REQUEST           => 400;
use constant HTTP_NOT_FOUND             => 404;
use constant HTTP_METHOD_NOT_ALLOWED    => 405;
use constant HTTP_PRECONDITION_FAILED   => 412;
use constant HTTP_INTERNAL_SERVER_ERROR => 500;


sub encodeReturnJSON {
	my ($returnData) = @_;

	my $data = {data => $returnData};

	my $json = encode_json($data);
	return $json;
}


sub encodeErrorMessageJSON {
	my ($error) = @_;

	my $data = {errorMessage => $error};

	my $json = encode_json($data);
	return $json;
}


sub encodeSuccessJSON {
	my ($message) = @_;

	my $data = {status => $message};

	my $json = encode_json($data);
	return $json;
}


sub executeControlDispatch {
	my ($clientId, $verbArray, $resultToGet) = @_;

	my $request = Slim::Control::Request->new($clientId, $verbArray);
	my $resp = $request->execute();
	if ( $request->isStatusError() ) {
		$log->error('Control dispatch Failed : ' . $request->getStatusText());
		return;
	} else {
		if ( $resultToGet ) {
			return $request->getResult($resultToGet);
		} else {
			return 1;
		}		
	}
}

sub callbackError {
	my ($callback, $errorText, $httpCode) = @_;

	my $json = Plugins::PluginManagerAPI::Utilities::encodeErrorMessageJSON($errorText);
	$callback->($httpCode, $json);

	return;	

}

sub extractPluginNameFromID {
	my ($pluginID) = @_;

	my @elem = split /::/, $pluginID;
	
	if ($elem[0] eq 'Slim') {
		return $elem[2];
	} elsif ( $elem[0] eq 'Plugins' ) {
		return $elem[1];		
	} else {
		return;
	}
}

sub isSlimPlugin {
	
	my ($pluginID) = @_;
	my @elem = split /::/, $pluginID;	
	
	if ($elem[0] eq 'Slim') {
		return 1;
	}
	return;
}


1;


