<?php

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

use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\farm_ui_theme\Form\AssetForm;
use Drupal\farm_ui_theme\Form\LogForm;
use Drupal\farm_ui_theme\Form\PlanForm;

/**
 * Implements hook_theme().
 */
function farm_ui_theme_theme($existing, $type, $theme, $path) {
  return [
    'html__asset__map_popup' => [
      'base hook' => 'html',
    ],
    'menu_local_tasks__farm' => [
      'base hook' => 'menu_local_tasks',
    ],
    'menu_local_task__secondary' => [
      'base hook' => 'menu_local_task',
    ],
    'page__asset__map_popup' => [
      'base hook' => 'page',
    ],
    // Implement the node edit form theme hook.
    // See https://www.drupal.org/project/gin/issues/3342164
    'node_edit_form' => [
      'render element' => 'form',
    ],
  ];
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function farm_ui_theme_theme_suggestions_menu_local_task(array $variables) {
  // Add suggestions for primary and secondary task levels.
  $suggestions = [];
  if (isset($variables['element']['#level'])) {
    $suggestions[] = 'menu_local_task__' . $variables['element']['#level'];
  }
  return $suggestions;
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function farm_ui_theme_theme_suggestions_menu_local_tasks(array $variables) {
  return ['menu_local_tasks__farm'];
}

/**
 * Implements hook_entity_form_display_alter().
 */
function farm_ui_theme_entity_form_display_alter(EntityFormDisplayInterface $form_display, array $context) {

  // Only alter farm entity types.
  $entity_types = ['asset', 'log', 'plan'];
  if (!in_array($context['entity_type'], $entity_types)) {
    return;
  }

  // Ask modules for a list of field group items.
  $field_map = \Drupal::moduleHandler()->invokeAll(
    'farm_ui_theme_field_group_items',
    [$context['entity_type'], $context['bundle']],
  );

  // Apply the field group mapping if not already specified on the form display.
  foreach ($field_map as $field_id => $field_group) {
    if (($renderer = $form_display->getRenderer($field_id)) && !$renderer->getThirdPartySetting('farm_ui_theme', 'field_group', FALSE)) {
      $renderer->setThirdPartySetting('farm_ui_theme', 'field_group', $field_group);
    }
  }
}

/**
 * Implements hook_farm_ui_theme_field_group_items().
 */
function farm_ui_theme_farm_ui_theme_field_group_items(string $entity_type, string $bundle) {

  // Define base fields for asset, log, and plans on behalf of core modules.
  $fields = [
    'name' => 'default',
    'status' => 'meta',
    'flag' => 'meta',
    'file' => 'file',
    'image' => 'file',
    'revision' => 'revision',
    'revision_log_message' => 'revision',
  ];
  switch ($entity_type) {
    case 'asset':
      $fields['owner'] = 'meta';
      $fields['parent'] = 'parent';
      $fields['intrinsic_geometry'] = 'location';
      $fields['is_location'] = 'location';
      $fields['is_fixed'] = 'location';
      $fields['id_tag'] = 'id_tag';
      break;

    case 'log':
      $fields['timestamp'] = 'default';
      $fields['category'] = 'meta';
      $fields['owner'] = 'meta';
      $fields['asset'] = 'asset';
      $fields['geometry'] = 'location';
      $fields['location'] = 'location';
      $fields['is_movement'] = 'location';
      $fields['quantity'] = 'quantity';
      break;

    case 'plan':
      break;

    default:
      $fields = [];
  }
  return $fields;
}

/**
 * Implements hook_gin_content_form_routes().
 */
function farm_ui_theme_gin_content_form_routes() {
  $routes = [];
  $entity_types = ['asset', 'log', 'plan'];
  foreach ($entity_types as $entity_type) {
    $routes[] = "entity.$entity_type.add_form";
    $routes[] = "entity.$entity_type.edit_form";
  }
  return $routes;
}

/**
 * Implements hook_entity_type_build().
 */
function farm_ui_theme_entity_type_build(array &$entity_types) {

  // Override the default add and edit form class.
  $target_entity_types = [
    'asset' => AssetForm::class,
    'log' => LogForm::class,
    'plan' => PlanForm::class,
  ];
  foreach ($target_entity_types as $entity_type => $form_class) {
    if (isset($entity_types[$entity_type])) {
      $entity_types[$entity_type]->setFormClass('add', $form_class);
      $entity_types[$entity_type]->setFormClass('edit', $form_class);
    }
  }
}

/**
 * Implements hook_element_info_alter().
 */
function farm_ui_theme_element_info_alter(array &$info) {
  if (isset($info['farm_map'])) {
    $info['farm_map']['#attached']['library'][] = 'farm_ui_theme/map';
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function farm_ui_theme_form_quick_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#attached']['library'][] = 'farm_ui_theme/quick';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'help_block') {
    $variables['#attached']['library'][] = 'farm_ui_theme/help';
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_toolbar(&$variables) {
  $variables['#attached']['library'][] = 'farm_ui_theme/toolbar';
}

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function farm_ui_theme_block_view_farm_powered_by_block_alter(array &$build, BlockPluginInterface $block) {
  $build['#attached']['library'][] = 'farm_ui_theme/footer';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_field__flag(array &$variables) {
  $variables['#attached']['library'][] = 'farm_ui_theme/flag';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_asset__full(&$variables) {
  farm_ui_theme_build_stacked_twocol_layout($variables, 'asset');
  $variables['#attached']['library'][] = 'farm_ui_theme/layout';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_log__full(&$variables) {
  farm_ui_theme_build_stacked_twocol_layout($variables, 'log');
  $variables['#attached']['library'][] = 'farm_ui_theme/layout';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'farm_ui_theme/regions';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_page__dashboard(&$variables) {
  $variables['#attached']['library'][] = 'farm_ui_theme/dashboard';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_plan__full(&$variables) {
  farm_ui_theme_build_stacked_twocol_layout($variables, 'plan');
  $variables['#attached']['library'][] = 'farm_ui_theme/layout';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function farm_ui_theme_preprocess_views_view(&$variables) {
  $variables['#attached']['library'][] = 'farm_ui_theme/views';
}

/**
 * Splits content into a stacked two-column layout.
 *
 * @param array $variables
 *   A $variables array that contains a 'content' item, which will be replaced
 *   by a stacked two-column layout.
 * @param string $entity_type
 *   The entity type.
 */
function farm_ui_theme_build_stacked_twocol_layout(array &$variables, string $entity_type) {

  // Ask modules for a list of region items.
  $region_items = \Drupal::moduleHandler()->invokeAll('farm_ui_theme_region_items', [$entity_type]);

  // Split the content items into regions.
  $regions = [];
  foreach ($variables['content'] as $index => $item) {
    $region = 'first';
    foreach ($region_items as $region_name => $items) {
      if (in_array($index, $items)) {
        $region = $region_name;
        break;
      }
    }
    $regions[$region][$index] = $item;
  }

  // Build the layout.
  /** @var \Drupal\Core\Layout\LayoutInterface $layoutInstance */
  $layout = \Drupal::service('plugin.manager.core.layout')->createInstance('layout_twocol', []);
  $variables['content'] = $layout->build($regions);
}

/**
 * Implements hook_farm_ui_theme_region_items().
 */
function farm_ui_theme_farm_ui_theme_region_items(string $entity_type) {

  // Define common asset, log, and plan region items on behalf of core modules.
  switch ($entity_type) {

    case 'asset':
      return [
        'top' => [
          'geometry',
        ],
        'first' => [],
        'second' => [
          'image',
          'inventory',
          'is_location',
          'is_fixed',
          'location',
          'owner',
          'status',
          'type',
        ],
        'bottom' => [
          'api',
          'file',
        ],
      ];

    case 'log':
      return [
        'top' => [
          'geometry',
        ],
        'first' => [],
        'second' => [
          'image',
          'owner',
          'status',
          'type',
        ],
        'bottom' => [
          'file',
        ],
      ];

    case 'plan':
      return [
        'top' => [],
        'first' => [],
        'second' => [
          'image',
          'status',
          'type',
        ],
        'bottom' => [
          'file',
        ],
      ];

    default:
      return [];
  }
}

/**
 * Implements hook_farm_update_exclude_config().
 */
function farm_ui_theme_farm_update_exclude_config() {

  // Exclude config that we have overridden in hook_install() or the
  // farm_ui_theme.overrider service.
  return [
    'block.block.gin_local_actions',
    'block.block.gin_content',
  ];
}
