<?php

/**
 * @file
 * The social_like module.
 */

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_entity_view_alter().
 */
function social_like_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  if ($display->getComponent('like_and_dislike')) {
    // Check if the current user has permission
    // if not, hide the like and dislike.
    if (!\Drupal::currentUser()->hasPermission('view like widget')) {
      unset($build['like_and_dislike']);
    }
    else {
      $build['#attached']['library'][] = 'core/drupal.dialog.ajax';
    }
  }
}

/**
 * Implements hook_views_pre_render().
 */
function social_like_views_pre_render(ViewExecutable $view) {
  // Set the amount of likes as the title.
  if ($view->id() == 'who_liked_this_entity') {
    $view->setTitle(t('@amount like(s)', ['@amount' => $view->total_rows]));
  }
}

/**
 * Implements hook_entity_insert().
 */
function social_like_entity_insert(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'vote') {
    social_like_invalidate_cache($entity);
  }
}

/**
 * Implements hook_entity_delete().
 */
function social_like_entity_delete(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'vote') {
    social_like_invalidate_cache($entity);
  }
}

/**
 * Implements hook_invalidate_cache().
 */
function social_like_invalidate_cache(EntityInterface $entity) {
  $cache_tag = [
    $entity->getEntityTypeId() . ':' . $entity->id(),
    'config:views.view.who_liked_this_entity',
  ];
  Cache::invalidateTags($cache_tag);
}

/**
 * Implements hook_preprocess().
 */
function social_like_preprocess_like_and_dislike_icons(&$variables) {
  $bundle = $variables['entity_type'];
  if ($entity = \Drupal::entityTypeManager()->getStorage($variables['entity_type'])->load($variables['entity_id'])) {
    $bundle = $entity->bundle();

    $entity_type = $entity->getEntityType();
    $entity_type_bundle_info = \Drupal::service('entity_type.bundle.info');
    $entity_bundles = $entity_type_bundle_info->getBundleInfo($entity_type->id());

    if (array_key_exists($bundle, $entity_bundles)) {
      $bundle = $entity_bundles[$bundle]['label'];
    }

    // If the entity is unpublished and of type comment disable voting.
    if (!$entity->isPublished() && $entity->getEntityTypeId() === 'comment') {
      foreach ($variables['icons'] as &$icon) {
        $icon['attributes']->addClass('disable-status');
      }
    }
  }
  $variables['modal_title'] = t('Members who liked this @content', ['@content' => $bundle]);
}
