<?php

/**
 * @file
 * The farmOS UI Map module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_farm_dashboard_panes().
 */
function farm_ui_map_farm_dashboard_panes() {
  return [
    'dashboard_map' => [
      'block' => 'map_block',
      'args' => [
        'map_type' => 'dashboard',
      ],
      'region'  => 'top',
    ],
  ];
}

/**
 * Implements hook_module_implements_alter().
 */
function farm_ui_map_module_implements_alter(&$implementations, $hook) {

  // Ensure that this module's hook_views_pre_render() runs first.
  if ($hook == 'views_pre_render') {
    $module = 'farm_ui_map';
    $group = $implementations[$module];
    unset($implementations[$module]);
    $implementations = array_merge([$module => $group], $implementations);
  }
}

/**
 * Implements hook_menu_local_actions_alter().
 */
function farm_ui_map_menu_local_actions_alter(&$local_actions) {
  // Include asset.add.log.* location actions on the asset.map_popup route.
  foreach ($local_actions as $id => $local_action) {
    if (strpos($id, 'farm.actions:farm.asset.add.log.') === 0) {
      $local_actions[$id]['appears_on'][] = 'farm_ui_map.asset.map_popup';
    }
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_map_preprocess_block__farm_local_actions_block(&$variables, $block) {
  if (\Drupal::routeMatch()->getRouteName() === 'farm_ui_map.asset.map_popup') {
    $variables['content']['#dropbutton_type'] = 'small';
  }
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function farm_ui_map_asset_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  /** @var \Drupal\farm_entity\Plugin\Asset\AssetType\AssetTypeInterface $entity */

  // Bail if not the map_popup view mode.
  if ($view_mode !== 'map_popup') {
    return $build;
  }

  // The default view mode is used if a map_popup view mode is not provided.
  // Alter the default view mode to only include common fields.
  $view_mode_options = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle('asset', $entity->bundle());
  if (!array_key_exists($view_mode, $view_mode_options)) {
    $common_fields = ['name', 'type', 'flag', 'notes', 'location'];
    $build = array_filter($build, function ($key) use ($common_fields) {
      return strpos($key, '#') === 0 || in_array($key, $common_fields);
    }, ARRAY_FILTER_USE_KEY);
  }

  return $build;
}
