<?php

namespace Drupal\Core\Database\Driver\autoslave\Install;

use Drupal\Core\Database\Install\Tasks as InstallTasks;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Connection as DatabaseConnection;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;

/**
 * Specifies installation tasks for AutoSlave driver. (Just a wrapper for the 'master' DB)
 */
class Tasks extends InstallTasks {
  protected $pdoDriver = '';

  /**
   * Returns a human-readable name string for the backend databases.
   */
  public function name() {
    $conn = Database::getConnection();
    if ($conn->driver() != 'autoslave') {
      return t('Default connection is not an AutoSlave driver?!?');
    }
    return $this->connectionStatusTable($conn);
  }

  /**
   * Format autoslave connection info in a table.
   *
   * @param \Drupal\Core\Database\Connection $conn
   *   The database connection to inspect.
   */
  public function connectionStatusTable(DatabaseConnection $conn) {
    $output = '';
    $key = $conn->getKey();
    $target = $conn->getTarget();
    $msg = [];
    $pool = $conn->getPool();
    $master_pool = [];
    foreach ($pool['master'] as $target => $conninfos) {
      if ($conn->determineMasterTarget() == $target) {
        $target = '<strong>' . $target . '</strong>';
      }
      $master_pool[] = $target;
    }
    $slave_pool = [];
    foreach ($pool['slave'] as $target => $conninfos) {
      if ($conn->determineSlaveTarget() == $target) {
        $target = '<strong>' . $target . '</strong>';
      }
      $slave_pool[] = $target;
    }
    $msg[] = '<strong>Master pools:</strong> (' . implode(', ', $master_pool) . ')';
    $msg[] = '<strong>Slave pools:</strong> (' . implode(', ', $slave_pool) . ')';
    $path = '/' . \Drupal::service('extension.path.resolver')->getPath('module', 'autoslave') . '/icons/';
    $rows = [];
    foreach ($pool['all'] as $id => $conninfo) {
      if ($conninfo['driver'] == 'autoslave') {
        $icon = 'message-16-ok.png';
        $message = t('OK');
        $dsn = 'AutoSlave';
      }
      else {
        $status = $conn->checkConnection($id);
        if (is_object($status)) {
          $icon = 'message-16-error.png';
          $message = $status->getMessage();
        }
        elseif ($status === TRUE) {
          $icon = 'message-16-ok.png';
          $message = t('OK');
        }
        else {
          $icon = 'message-16-error.png';
          $message = t('Could not acquire status');
        }
        $dsn = $conninfo['driver'] . '://' . $conninfo['host'];
      }
      $status = '<img title="' . $message . '" src="' . Url::fromUserInput($path . $icon)->toString() . '"/>';
      $status = Markup::create($status);
      $rows[] = [$id, $conninfo['target'], $dsn, $status];
    }

    $build = [];
    $build['table'] = [
      '#type' => 'table',
      '#header' => [t('ID'), t('Target'), t('Connection'), t('Status')],
      '#rows' => $rows,
    ];

    return $build;
  }

}
