<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\nodehive_core\Entity\Space;

/**
 * Provides a 'NodeHiveSpacesBlock' block.
 *
 * @DashboardBlock(
 *   id = "node_hive_spaces_block",
 *   name = @Translation("NodeHive Spaces"),
 *   category = "NodeHive",
 *   id_category = "nodehive"
 * )
 */
class NodeHiveSpacesBlock extends DashboardBlockBase implements ContainerFactoryPluginInterface {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    // Query all spaces.
    $spaces_query = $this->entityTypeManager->getStorage('nodehive_space')->getQuery()
      ->accessCheck(TRUE)
      ->condition('status', 1);

    $space_ids = $spaces_query->execute();

    // Load all Space entities.
    $spaces = Space::loadMultiple($space_ids);

    $build['spaces_table'] = [
      '#type' => 'table',
      '#attributes' => [
        'class' => ['text-sm'],
      ],
    ];

    foreach ($spaces as $space) {
      $url = $space->toUrl();
      $view_link_renderable = [
        '#type' => 'link',
        '#title' => $space->label(),
        '#url' => $url,
      ];

      // Fetch the first URL from the 'url' field if set.
      $external_url = '';
      if (!$space->get('space_url')->isEmpty()) {
        $first_link = $space->get('space_url')->first()->getValue();
        $external_url = $first_link['uri'] ?? '';
      }

      $open_editor_label = (string) $this->t('Open Editor');
      $visit_label = (string) $this->t('Visit ↗');
      $build['spaces_table'][] = [
        'favicon' => [
          '#markup' => '<img class="favicon" src="https://www.google.com/s2/favicons?sz=32&domain=' . $external_url . '">',
        ],
        'title' => $view_link_renderable,
        'editor' => [
          '#type' => 'markup',
          '#markup' => '<a class="button button--extrasmall" href="/space/' . $space->id() . '/visualeditor">' . $open_editor_label . '</a>',
        ],
        'link' => [
          '#type' => 'markup',
          '#markup' => '<a class="button button--extrasmall" href="' . $external_url . '">' . $visit_label . '</a>',
        ],
      ];
    }

    $build['spaces_table']['#attached'] = [
      'library' => [
        'nodehive_core/node',
      ],
    ];

    return $build;
  }

}
