<?php

use Zend\Loader\AutoloaderFactory;
use P4\Connection\Connection;
use Groups\Model\Group;
use Zend\Http\Client as HttpClient;
use Zend\Json\Json;
use Zend\Mvc\MvcEvent;
use Zend\ServiceManager\ServiceLocatorInterface as ServiceLocator;

define('BASE_PATH', __DIR__);

$debug = 4;
$preview = true;

// setup autoloading
set_include_path(BASE_PATH);
include 'library/Zend/Loader/AutoloaderFactory.php';
AutoloaderFactory::factory(
    array(
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                'P4'     => BASE_PATH . '/library/P4',
                'Record' => BASE_PATH . '/library/Record',
                'Zend'   => BASE_PATH . '/library/Zend',
            )
        )
    )
);

// config is needed for parameters among other things
if (!file_exists('jiraconfig.php')) {
    echo "Cannot find the test config file 'jiraconfig.php'\n";
    return;
}

$config = include 'jiraconfig.php';

if (!array_key_exists('jira', $config)) {
    echo "Cannot find the 'jira' configuration block in the jiraconfig.php file.\n";
    return;
}

$jconfig = $config['jira'];
 
$jconfig['host'] = rtrim($jconfig['host'], '/');
if ($jconfig['host'] && strpos(strtolower($jconfig['host']), 'http') !== 0) {
    $jconfig['host'] = 'http://' . $jconfig['host'];
}

echo "JIRA host: ", $jconfig['host'], "\n";

$url    = $jconfig['host'] . '/rest/api/latest/project' ;
$client = new HttpClient;
$client->setUri($url)
                   ->setHeaders(array('Content-Type' => 'application/json'))
                   ->setMethod('get');
 
$options = $config + array('http_client_options' => array());
$options = (array) $options['http_client_options'];
if (isset($options['hosts'][$client->getUri()->getHost()])) {
    $options = (array) $options['hosts'][$client->getUri()->getHost()] + $options;
}
unset($options['hosts']);
$client->setOptions($options);

if ($jconfig['user']) {
    $client->setAuth($jconfig['user'], $jconfig['password']);
}

echo 'Making request to ', $url, "\n" ;

try {
    $response = $client->dispatch($client->getRequest());
    echo "  Status code: ", $response->getStatusCode(), " ", $response->getReasonPhrase(), "\n";
    if ( $response->isSuccess()) {
        $projects = json_decode($response->getBody(), true) ;
        echo "JIRA Projects returned: ", count($projects), "\n";
        foreach($projects as $proj) {
           echo " ",$proj['key'];
        }
        echo " \n";
    } else {
        echo "Failed!\n";
    }
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
    echo $e;
    echo "\n";
}