#!/usr/bin/env php
<?php

/**
 * This is a simple batch file example.
 * you can try php batch.php -f file.csv
 * It will generate a file.csv.out
 *
 * Don't hesitate to copy and build your own batch script
 */

require dirname(__FILE__) . '/../scripts/autoload.php';

function displayManual()
{
    $help = <<<HELP
Usage: bin/batch -f file.csv -i IDENTIFIER -p 'PASSWORD' [-s time] [-e production|sandbox] [-o output_file]

Arguments:
    -f CSV input file (mandatory)
    -i Dalenys IDENTIFIER (mandatory)
    -p Dalenys PASSWORD. Use single quotes if your password contains special chars (mandatory if configuration file not set)
    -c Configuration file (mandatory if password not set)
    -s Time in milliseconds to wait between each transactions (optional)
    -e Environment: production or sandbox (default=production) (optional)
    -o Output file. Default: file.out.csv (optional)

HELP;

    echo $help;
    exit(1);
}

/**
 * @param $file
 * @return string
 */
function validateFile($file)
{
// Get full path of file
    $file = realpath($file);

    // Validate file
    if (!file_exists($file)) {
        echo "File {$file} does not exists";
        exit(1);
    } else {
        if (!is_readable($file)) {
            echo "File {$file} is not readable";
            exit(1);
        }
        return $file;
    }
}

function getPasswordFromConfigurationFile($identifier, $file)
{
    $password = null;

    // Parse configuration file
    $configFile        = validateFile($file);
    $configFileContent = file_get_contents($configFile);
    $config            = json_decode($configFileContent, true);
    
    if (!$config || !isset($config['accounts'][0])) {
        echo "Configuration file is not a well formed JSON file\n";
        exit(1);
    } else {
        foreach ($config['accounts'] as $account) {
            if (!isset($account['IDENTIFIER']) || !isset($account['PASSWORD'])) {
                echo "Configuration file is not a well formed JSON file\n";
                exit(1);
            }
            if ($account['IDENTIFIER'] == $identifier) {
                $password = $account['PASSWORD'];
            }
        }

        if ($password === null) {
            echo "Configuration file does not contains a \"{$identifier}\" record\n";
            exit(1);
        }
    }

    return $password;
}

// Expect -f file argument
$args = getopt('f:i:p:s:e:o:c:');

// Script arguments handling (simple version)
if (!isset($args['f']) || !isset($args['i'])) {
    displayManual();
} elseif (!isset($args['p']) && !isset($args['c'])) {
    displayManual();
} else {
    $identifier = $args['i'];

    // Password handling
    if (isset($args['p'])) {
        $password = $args['p'];
    } else {
        $password = getPasswordFromConfigurationFile($identifier, $args['c']);
    }

    $file = validateFile($args['f']);
}

// Output file
if (isset($args['o'])) {
    $outputFile = $args['o'];
} else {
    // Output file = input_file.out.csv
    $outputFile = preg_replace('/(.*)\.csv/', '$1.out.csv', $file);
}

echo "Output file name: {$outputFile}\n";

// Instantiate
if (isset($args['e']) && $args['e'] = 'sandbox') {
    $batchApi = Dalenys_Api_ClientBuilder::buildSandboxBatchClient($identifier, $password);
} else {
    $batchApi = Dalenys_Api_ClientBuilder::buildProductionBatchClient($identifier, $password);
}

// Input file
$batchApi->setInputFile($file);

// Console log
$batchApi->attach(new Dalenys_Api_Batch_Observer_Debug());

// File report (file.out.csv)
$batchApi->attach(new Dalenys_Api_Batch_Observer_FileReport($outputFile));

if (isset($args['s'])) {
    echo "Sleep time: {$args['s']} msec\n";

    // Wait some milliseconds between each calls.
    $batchApi->attach(new Dalenys_Api_Batch_Observer_Sleep(intval($args['s'])));
}

$batchApi->run();

