#!/usr/bin/php
<?php

use Phalcon\Di\FactoryDefault\Cli as CliDI;
use Phalcon\Cli\Console as ConsoleApp;
use Phalcon\Config\Adapter\Ini as ConfigIni;
use Huuuk\Queues\QueueManager;

define('VERSION', '1.0.0');

// Using the CLI factory default services container
$di = new CliDI();

// Define path to application directory
defined('APP_PATH')
|| define('APP_PATH', realpath(dirname(__DIR__)) . '/');

/**
 * Register the autoloader and tell it to register the tasks directory
 */
$loader = new \Phalcon\Loader();
$loader->registerDirs(
    array(
        APP_PATH . 'app/tasks',
        APP_PATH . 'app/jobs',
        APP_PATH . 'app/models',
    )
);
$loader->register();

require APP_PATH . 'vendor/autoload.php';

$config = new ConfigIni(APP_PATH . 'app/config/config.ini');
$di->set('config', $config);

/**
 * Process the console arguments
 */
$arguments = array();
foreach ($argv as $k => $arg) {
    if ($k == 1) {
        $arguments['task'] = $arg;
    } elseif ($k == 2) {
        $arguments['action'] = $arg;
    } elseif ($k >= 3) {
        $arguments['params'][] = $arg;
    }
}

// Define global constants for the current task and action
define('CURRENT_TASK',   (isset($argv[1]) ? $argv[1] : null));
define('CURRENT_ACTION', (isset($argv[2]) ? $argv[2] : null));

$di->set('db', function () use ($config) {
    $config = $config->get('database')->toArray();

    $dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
    unset($config['adapter']);

    return new $dbClass($config);
});

$queueManager = new QueueManager($config);
$di->set('queue', $queueManager->getQueue());

// Create a console application
$console = new ConsoleApp();
$console->setDI($di);

try {
    // Handle incoming arguments
    $console->handle($arguments);
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();
    exit(255);
}