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

require __DIR__ . '/../../vendor/autoload.php';

use tubalmartin\CssMin\Minifier;
use tubalmartin\CssMin\Tests\FineDiff\Render\Cli as CliRenderer;
use cogpowered\FineDiff\Diff;

$opts = getopt(
    't:f:',
    array('keep-sourcemap', 'keep-sourcemap-comment', 'remove-important-comments', 'linebreak-position:')
);

if (empty($opts['t'])) {
    fwrite(
        STDERR,
        'You need to provide -t argument to run the specified test i.e. "php ./tests/bin/runner -t mui"' . PHP_EOL
    );
    die(1);
}

$expectation = $opts['t'];
$fixture = $expectation;

if (!empty($opts['f'])) {
    $fixture = $opts['f'];
}

$fixtureFile = __DIR__ .'/../fixtures/'. $fixture .'.css';
$expectationFile = __DIR__ .'/../expectations/'. $expectation .'.css';

if (!is_readable($fixtureFile) || !is_readable($expectationFile)) {
    fwrite(
        STDERR,
        'Either test fixture or expectation is missing or not readable' . PHP_EOL
    );
    die(1);
}

$minifier = new Minifier;

if (isset($opts['keep-sourcemap']) || isset($opts['keep-sourcemap-comment'])) {
    $minifier->keepSourceMapComment();
}

if (isset($opts['remove-important-comments'])) {
    $minifier->removeImportantComments();
}

if (!empty($opts['linebreak-position'])) {
    $minifier->setLineBreakPosition($opts['linebreak-position']);
}

$fixture = file_get_contents($fixtureFile);
$expectation = file_get_contents($expectationFile);
$output = $minifier->run($fixture);

if (strcmp($output, $expectation) === 0) {
    fwrite(
        STDOUT,
        "\x1b[30m\x1b[42m OK \x1b[0m" . PHP_EOL
    );
    die(0);
} else {
    $diff = new Diff;
    $cliRenderer = new CliRenderer;
    $diffString = $cliRenderer->process($expectation, $diff->getOpcodes($expectation, $output));
    fwrite(
        STDERR,
        "\x1b[37m\x1b[41m FAILURE \x1b[0m" . PHP_EOL .
        '---' . PHP_EOL .
        $diffString . PHP_EOL .
        '---' . PHP_EOL
    );
    die(1);
}
