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

/**
 * @file
 * This is the CLI controller for aspect_ratio.
 */

namespace AKlump\AspectRatio;

use AKlump\LoftLib\Bash\Color;
use AKlump\LoftLib\Bash\Output;

define('ROOT', dirname(__FILE__));

try {
  require ROOT . '/includes/bootstrap.inc';

  $ratios = $aspect_ratio->getAllRatios();
  if ($cli->hasParam('json')) {
    print json_encode(array_values($ratios)) . PHP_EOL;
  }
  else {
    $rows = [];
    $nearby = FALSE;

    // Remove the original.
    array_shift($ratios);
    foreach ($ratios as $ratio) {
      $item = [];

      $color = '';

      $item['Type'] = $ratio['type'];
      $item['Ratio'] = $ratio['ratio_x'];
      if ($ratio['ratio_y'] != 1 || strstr($ratio['ratio_x'], '.') === FALSE) {
        $item['Ratio'] .= ':' . $ratio['ratio_y'];
      }
      $item['Dimensions'] = round($ratio['width'], 0) . ' x ' . round($ratio['height'], 0);
      $item['Variance'] = $ratio['difference_y'];
      $item['Variance %'] = round(trim($ratio['difference_y_percent'], '%'), 1) . '%';

      if (!$nearby && $ratio['type'] === 'nearby') {
        $nearby = TRUE;

        // Setup color for nicest ratio.
        $color = 'dark grey on green';
      }
      $rows[] = [
        'color' => $color,
        'data' => $item,
      ];
    }
    $cell_keys = array_keys($rows[0]['data']);

    // Create the header row.
    array_unshift($rows, [
      'color' => 'white',
      'data' => array_combine($cell_keys, $cell_keys),
    ]);

    // Setup alignment for all columns, defaults to right.
    $alignment = [
      'Type' => 'left',
    ];
    $alignment += array_fill_keys($cell_keys, 'right');

    // Print the output as a table.
    print Output::columns($rows, $alignment, "    ") . PHP_EOL;
  }
}
catch (\Exception $exception) {
  echo Color::wrap('red', $exception->getMessage() . PHP_EOL);
  exit(1);
}

exit(0);
