#!/usr/bin/env php
<?php
    require dirname(__DIR__) . '/app/config/bootstrap.php';

    $xml_config = \app\lib\Library::retrieve('xml_configuration_file');
    if ( !$xml_config || !$xml_config = realpath($xml_config) ) {
        die(
            "\nA valid xml_configuration_file must be specified in "
            . "app/config/bootstrap.php for VPU to work."
        );
    }

    $vpu = new \app\lib\VPU();

    $sandbox_errors = \app\lib\Library::retrieve('sandbox_errors');
    if ( $sandbox_errors ) {
        error_reporting(\app\lib\Library::retrieve('error_reporting'));
        set_error_handler(array($vpu, 'handle_errors'));
    }

    $results = $vpu->run_with_xml($xml_config);
    $results = $vpu->compile_suites($results, 'cli');

    if ( $sandbox_errors ) {
        restore_error_handler();
    }

    $suites = $results['suites'];
    $stats = $results['stats'];
    $errors = $vpu->get_errors();
    $to_view = compact('suites', 'stats', 'errors');

    $filename = realpath(
        \app\lib\Library::retrieve('snapshot_directory')
    ) . '/' . date('Y-m-d_G-i') . '.html';

    $handle = @fopen($filename, 'a');
    if ( !$handle ) {
        die(
            "\nThere was an error creating the snapshot.  Please ensure that "
            . "the snapshot_directory in app/config/bootstrap.php exists and "
            . "has the proper permissions."
        );
    }

    $view = new \app\core\View();
    $contents = $view->render('partial/test_results', $to_view);

    fwrite($handle, $contents);
    fclose($handle);

    echo "\nSnapshot successfully created at {$filename}.";

    $store_statistics = \app\lib\Library::retrieve('store_statistics');
    if ( !$store_statistics ) {
        exit;
    }

    $db_options = \app\lib\Library::retrieve('db');
    $db = new $db_options['plugin']();
    if ( !$db->connect($db_options) ) {
        die(
            "\nThere was an error connecting to the database:\n"
            . implode(' ', $db->get_errors())
        );
    }

    $now = date('Y-m-d H:i:s');
    foreach ( $stats as $key => $stat ) {
        $data = array(
            'run_date'   => $now,
            'failed'     => $stat['failed'],
            'incomplete' => $stat['incomplete'],
            'skipped'    => $stat['skipped'],
            'succeeded'  => $stat['succeeded']
        );
        $table = ucfirst(rtrim($key, 's')) . 'Result';
        if ( !$db->insert($table, $data) ) {
            die(
                "\nThere was an error inserting a record into the database:\n"
                . implode(' ', $db->get_errors())
            );
        }
    }

    echo "\nThe statistics generated during this test run were successfully "
        . "stored.";
?>
