#!/usr/bin/env php
<?php
/*
 * this script generates auto-complete classes from ini files
 */
defined('APPLICATION_ROOT')
    || define('APPLICATION_ROOT', realpath(dirname(__FILE__) . '/..'));

set_include_path(implode(PATH_SEPARATOR, array(
    APPLICATION_ROOT . '/lib',
    get_include_path(),
)));

require 'Core/Console/Application.php';
$application = Core_Console_Application::getInstance();

/*
 * components mapping
 */
$map = array(
    'container' => array(
        'sourceName' => 'container.ini',
        'targetPath' => __DIR__ . '/../../app/lib/Core/Application/Component/Container.php',
        'template' => 'container.inc'
    ),
    'models' => array(
        'sourceName' => 'models.ini',
        'targetPath' => __DIR__ . '/../../app/lib/Core/Application/Component/Models.php',
        'template' => 'models.inc'
    ),
    'controller' => array(
        'sourceName' => 'container.ini',
        'targetPath' => __DIR__ . '/../../app/modules/ControllerAbstract.php',
        'template' => 'controller.inc'
    )
);

foreach($map as $config) {
    $configPath = __DIR__ . '/../../app/config/' . $config['sourceName'];

    if (!file_exists($configPath)) {
        echo sprintf(
            'Skipping source: "%s", file does not exist.' . "\n",
            $configPath
        );
        continue;
    }
    $parsedConfig = new Core_Config($configPath);
    $properties = '';
    foreach($parsedConfig->toArray() as $key => $params) {
        $class = $params['class'];
        $properties .= sprintf(
            " * @property %s \$%s\n",
            $class,
            $key
        );
    }

    $template = '<';
    $template .= '?php';
    $template .= "\n\n";
    $template .= file_get_contents(__DIR__ . '/component_templates/' . $config['template']);

    if (!file_exists(dirname($config['targetPath']))) {
        mkdir(dirname($config['targetPath']), 0777, true);
    }

    $sizeOld = 0;
    $hashOld = null;
    if (file_exists($config['targetPath'])) {
        $sizeOld = filesize($config['targetPath']);
        $hashOld = sha1(file_get_contents($config['targetPath']));
    }
    $size = file_put_contents(
        $config['targetPath'],
        sprintf(
            $template,
            $properties
        )
    );

    if (!$size) {
        echo sprintf(
            'Cannot write file "%s".%s',
            $config['targetPath'],
            "\n"
        );
        break;
    }

    $hashNew = sha1(file_get_contents($config['targetPath']));
    if ($size && $size == $sizeOld && $hashOld == $hashNew) {
        echo sprintf(
            'File "%s" not changed.' . "\n",
            $config['sourceName']
        );
    }
    else {
        echo sprintf(
            'Parsed config "%s" into file "%s" containing %s bytes.%s',
            $config['sourceName'],
            $config['targetPath'],
            $size,
            "\n"
        );
    }
}

