<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;

/**
 * FlowDrop hooks implementation.
 */
class FlowDropHooks {

  use StringTranslationTrait;

  /**
   * Implements hook_flowdrop_node_processor_info_alter().
   *
   * @param array<string, mixed> $data
   *   The processor info data.
   */
  #[Hook('flowdrop_node_processor_info_alter')]
  public function flowdropNodeProcessorInfoAlter(array &$data): void {}

  /**
   * Implements hook_toolbar().
   *
   * Adds a FlowDrop item to the admin toolbar for quick access.
   *
   * @return array<string, mixed>
   *   A render array for the toolbar item.
   */
  #[Hook('toolbar')]
  public function toolbar(): array {
    $items = [];

    // Check if the dashboard route exists before adding toolbar.
    if (!$this->routeExists("flowdrop.dashboard")) {
      return $items;
    }

    $items["flowdrop"] = [
      "#type" => "toolbar_item",
      "#weight" => 50,
      "tab" => [
        "#type" => "link",
        "#title" => $this->t("FlowDrop"),
        "#url" => Url::fromRoute("flowdrop.dashboard"),
        "#attributes" => [
          "title" => $this->t("FlowDrop workflow automation"),
          "class" => ["toolbar-icon", "toolbar-icon-flowdrop"],
        ],
      ],
      "#attached" => [
        "library" => [
          "flowdrop/toolbar",
        ],
      ],
    ];

    return $items;
  }

  /**
   * Checks if a route exists.
   *
   * @param string $routeName
   *   The route name.
   *
   * @return bool
   *   TRUE if the route exists, FALSE otherwise.
   */
  protected function routeExists(string $routeName): bool {
    try {
      /** @var \Drupal\Core\Routing\RouteProviderInterface $routeProvider */
      $routeProvider = \Drupal::service("router.route_provider");
      $routeProvider->getRouteByName($routeName);
      return TRUE;
    }
    catch (\Exception $e) {
      return FALSE;
    }
  }

}
