<?php

namespace Drupal\reader\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the channels block.
 *
 * @Block(
 *   id = "reader_channels",
 *   admin_label = @Translation("Reader channels"),
 *   category = @Translation("Reader")
 * )
 */
class Channels extends BlockBase {

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

    foreach (reader_get_implementators() as $module) {
      $function = $module . '_reader_channels';
      if (function_exists($function)) {
        $data = $function();
        if (!empty($data['channels'])) {
          $items = [];
          foreach ($data['channels'] as $channel) {
            $unread = !empty($channel->unread) ? ' (' .  $channel->unread .')' : '';
            $items[] = Link::fromTextAndUrl($channel->name . $unread, Url::fromRoute('reader.timeline', ['module' => strtr($module, '_', '-'), 'id' => $channel->uid], ['attributes' => ['class' => ['column-link']]]));
          }
          $channels[] = [
            'label' => $data['label'],
            'items' => $items,
          ];
        }
      }
    }

    return [
      '#theme' => 'reader_channels_list',
      '#channels' => $channels,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

}
