<?php

use Fifa\ConnectId\Command\Helpers\FileLogger;
use Fifa\ConnectId\Command\Helpers\ListenerTestPersonDetailsProvider;
use Fifa\ConnectId\Sdk\ActorResolver\SimpleActorResolver;
use Fifa\ConnectId\Sdk\Environment\Environment;
use Fifa\ConnectId\Sdk\Registration\Model\RegistrationFacadeSettings;
use Fifa\ConnectId\Sdk\Registration\RegistrationFacade;
use Fifa\ConnectId\Sdk\Storage\SqliteStorage;
use Fifa\ConnectId\Sdk\Util\File;
use Fifa\ConnectServiceBus\Sdk\Authentication\Model\ClientCredentials;
use Fifa\ConnectServiceBus\Sdk\Encryption\Decrypt\PrivateCertificateMemoryStorage;
use Fifa\ConnectServiceBus\Sdk\Encryption\Model\PrivateCertificate;
use Psr\Log\NullLogger;

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($argv[1]) || !file_exists($argv[1])) {
    throw new InvalidArgumentException('Path to INI file is incorrect.');
}

if (!isset($argv[2])) {
    throw new InvalidArgumentException('Missing parameter 2: organisation name (from INI file).');
}
$organisationParameter = $argv[2];

// install autoload from vendor
$dirname = str_replace('command', '', dirname(__FILE__));
require_once($dirname . '/vendor/autoload.php');

$logger = new FileLogger($dirname . '/debug.log', $organisationParameter);
$logger->debug("Start script $organisationParameter");

$iniSettings = parse_ini_file($argv[1], true);
if ($iniSettings === false) {
    throw new InvalidArgumentException('Given file is not correct INI file.');
}

$personDetailsProvider = new ListenerTestPersonDetailsProvider($logger);
if (isset($argv[3]) && class_exists($argv[3])) {
    $personDetailsProvider = new $argv[3]();
}

// execution time in seconds
$executionTime = 60;

// instance of PersonDetailsStorageInterface
$logger = new NullLogger();
$storage = SqliteStorage::getInstance($logger);

// instance of PrivateCertificateStorageInterface
$privateCertificate = new PrivateCertificate(
    File::getContents(str_replace('command', 'tests/' . $iniSettings['Credentials-' . $organisationParameter]['PrivateCertificate'], dirname(__FILE__))),
    $iniSettings['Credentials-' . $organisationParameter]['PrivateCertificatePassword']
);
$privateStorage = new PrivateCertificateMemoryStorage($privateCertificate);

// 1. Prepare client credentials
$clientCredentials = new ClientCredentials(
    $iniSettings['Credentials-' . $organisationParameter]['ClientId'],
    $iniSettings['Credentials-' . $organisationParameter]['SecretKey']
);

// 2. Prepare environment
$environment = Environment::Integration();

// 3. Create registration facade
$facadeSettings = new RegistrationFacadeSettings($storage, $executionTime);
$facadeSettings->setActorResolver(new SimpleActorResolver('PHP SDK actor (background-listener)'));
$facade = new RegistrationFacade($environment, $clientCredentials, $privateStorage, $logger, $facadeSettings);

// 4. Receive messages
$facade->configureEventHandlers($personDetailsProvider);
$facade->receiveMessages();