<?php
use Fifa\ConnectId\Command\BulkRegistration\Helpers\LocalDatabase;
use Fifa\ConnectId\Command\BulkRegistration\Helpers\PersonApi;
use Fifa\ConnectId\Command\BulkRegistration\Helpers\PlayerModel;
use Fifa\ConnectId\Command\BulkRegistration\Helpers\FileLogger;

if (!isset($argv[1]) || !isset($argv[2])) {
    throw new InvalidArgumentException('Please specify letters scope for current process.');
}

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

// instantiate helper classes
$database = new LocalDatabase();
$personApi = new PersonApi();
$logger = new FileLogger($dirname . DIRECTORY_SEPARATOR . 'debug.log');

// get players that will be used in current process
$lastNameStartChar = $argv[1];
$lastNameEndChar = $argv[2];
$players = $database->getNotRegisteredPlayersRange($lastNameStartChar, $lastNameEndChar);

$processId = getmypid();
$playersCount = count($players);
$logger->info("Running process $processId for $playersCount players.");

// register players
foreach ($players as $player) {

    $info = "Registering player '$player[0] $player[1]' from scope [$lastNameStartChar, $lastNameEndChar]";
    $logger->info($info);

    $personData = PlayerModel::createPersonData($player);
    $fifaUniqueId = $personApi->register($personData);
    $database->updateFifaUniqueId($player, $fifaUniqueId);
}

$logger->info("Process $processId finished registration.");