<?php

/**
 * @file
 * Contains hooks for youtubechannel module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\vendor\guzzlehttp\guzzle\src\Exception;
use Drupal\Core\Url;
use Drupal\Core\Link;

/**
 * Implements hook_help().
 */
function youtubechannel_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the better_exposed_filters module.
    case 'help.page.youtubechannel':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('YoutubeChannel is a module with a purpose to give you list of videos from a given youtube channel in your site.</p>');
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dt>' . t('Youtube channel settings') . '</dt>';
      $output .= '<dd>' . t('This module has a configuration page <a href=":YoutubeChannel">Youtube channel settings</a> where you can add api key and channel.This module creates a block to enable in the region.', [
  ':YoutubeChannel' => Url::fromRoute('youtubechannel.settings')->toString()
]). '</dd>';
      return $output;
    break;
  }
}

/**
 * Implements hook_page_top().
 */
function youtubechannel_page_top(array &$page_top) {
  $page_top['youtubechannel'] = [
    '#attached' => [
      'library' => [
        'youtubechannel/youtubechannel'
      ]
    ]
  ];
}

/**
 * Function to get video from youtube channel.
 */
function youtubechannelvideo() {
  $max_results = 5;
  $youtubechannel_config = \Drupal::config('youtubechannel.settings');
  $api_key = $youtubechannel_config->get('youtubechannel_api_key');
  $youtube_id = $youtubechannel_config->get('youtubechannel_id');
  $youtube_channel_id = $youtubechannel_config->get('youtubechannel_id');
  $max_results = $youtubechannel_config->get('youtubechannel_video_limit');
  $vars = array();
  
  /**
   * NEW API v3 feed.
   */
  // First, let's fetch the channel feed to get the upload playlist.
  $path = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id={$youtube_id}&maxResults=1&fields=pageInfo/totalResults,items/contentDetails/relatedPlaylists/uploads&key={$api_key}";
  $channeljson = '';

  try {
    $channeljson = (string) \Drupal::httpClient()->get($path, array('verify' => false))->getBody();
  }
  catch (RequestException $e) {
  }
  catch (BadResponseException $e) {
  }
  catch (\Exception $e) {
  }

  $channel_data = json_decode($channeljson, true);
  $uploads_id = $channel_data['items'][0]['contentDetails']['relatedPlaylists']['uploads'];

  if (!empty($channel_data['items'])) {
    $uri = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&}&maxResults={$max_results}&fields=pageInfo/totalResults,items/snippet(resourceId/videoId,title,thumbnails/default/url)&playlistId={$uploads_id}&key={$api_key}";
    try {
      $playlistjson = (string) \Drupal::httpClient()->get($uri, array('verify' => false))->getBody();
    }
    catch (RequestException $e) {
    }
    catch (BadResponseException $e) {
    }
    catch (\Exception $e) {
    }

    $feed_array = json_decode($playlistjson, true);

    if ($feed_array['pageInfo']['totalResults'] == 0) {
      return t("No videos available on this channel.");
    }

    $videos = array();
    foreach ($feed_array['items'] as $key => $value) {
      $youtube_id = $value['snippet']['resourceId']['videoId'];
      $title = $value['snippet']['title'];
      $videos[$youtube_id] = $value['snippet']['thumbnails']['default']['url'];
      //$videos[$youtube_id]['title'] = $title;
    }

    $vars['width'] = ['#plain_text' => $youtubechannel_config->get('youtubechannel_video_width')];
    $vars['height'] = ['#plain_text' => $youtubechannel_config->get('youtubechannel_video_height')];
    $vars['content'] = $videos;

    $url = Url::fromUri('https://www.youtube.com/channel/'.$youtube_channel_id);
    $channelLink = Link::fromTextAndUrl(t('Goto Youtube Channel'), $url);
    $channelLink = $channelLink->toRenderable();
    $channelLink['#attributes'] = array('target' => '_blank');
    $vars['channelLink'] = $channelLink;
  }
  else {
    $vars['show_error'] = true;

    $url = Url::fromRoute('youtubechannel.settings');
    $vars['config_link'] =  Link::fromTextAndUrl(t('admin page'), $url)->toString();
  }
  return $vars;
}

/**
 * Implements hook_theme().
 */
function youtubechannel_theme($existing, $type, $theme, $path) {
  $channel_data = youtubechannelvideo();
  return array(
    'youtubechannel_block' => array(
      'variables' => array('youtube_content' => $channel_data),
    ),
  );
}
