<?php

/**
 * @file
 * Contains opencase_defaults.module.
 */

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
use Drupal\opencase\EntityTypeRelationsWidget;

/**
 * Implements hook_help().
 */
function opencase_defaults_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the opencase_defaults module.
    case 'help.page.opencase_defaults':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('OpenCase Default Configuration') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_preprocess_page_title
 *  
 * Modify the page title to include more information 
 */
function opencase_defaults_preprocess_page_title(&$variables) {
  
   $route_name = \Drupal::routeMatch()->getRouteName();
    switch ($route_name) {
      case 'entity.oc_case.canonical':
        $case = \Drupal::routeMatch()->getParameter('oc_case');
        $variables['title'] = $case->getName() . ": Case Details and Files";
        break;
      case 'view.cases.page_1':
        $actor_id = \Drupal::routeMatch()->getParameter('actor_id');
        $actor = \Drupal::entityTypeManager()->getStorage('oc_actor')->load($actor_id); 
        $variables['title'] = $actor->getName() . ": Cases";
        break;
      case 'view.activities.page_1':
        $case_id = \Drupal::routeMatch()->getParameter('case_id');
        $case = \Drupal::entityTypeManager()->getStorage('oc_case')->load($case_id); 
        $variables['title'] = $case->getName() . ": Activities";
        break;
    }
}
/**
 * Implements hook_theme().
 */
function opencase_defaults_theme() {
  return [
    'opencase_defaults' => [
      'render element' => 'children',
    ],
  ];
}

/**
 * Implements hook_block_access
 *
 * Forbids the opencase_contextual_menu block on pages where it has no content.
 * (Without this, it was displaying an empty sidebar)
 */
function opencase_defaults_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {
  if ($operation == 'view' && $block->getPluginId() == 'opencase_contextual_menu') {
    $route_name = \Drupal::routeMatch()->getRouteName();
    $routes_where_it_should_be_shown = [
      'entity.oc_actor.canonical',
      'entity.oc_actor.edit_form',
      'view.cases.page_1',
      'entity.oc_case.canonical',
      'entity.oc_case.edit_form',
      'entity.oc_case.add_form',
      'view.activities.page_1',
      'entity.oc_activity.canonical',
      'entity.oc_activity.edit_form',
      'entity.oc_activity.add_form',
    ];
    return AccessResult::forbiddenIf(!in_array($route_name, $routes_where_it_should_be_shown))->addCacheableDependency($block);
  }

  // No opinion.
  return AccessResult::neutral();
}

function opencase_defaults_entity_base_field_info($entity_type) {
  $fields = array();
  
  // Add consent field to person
  if ($entity_type->id() === 'oc_actor') {
    $fields['consent'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Consent to data storage'))
      ->setDescription(t('Has this person explicitly consented to having their personal data stored on this system?'))
      ->setRevisionable(TRUE)
      ->setDefaultValue(FALSE)
      ->setRequired(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'weight' => -6,
      ));
  }

  // Add Involved Parties field to cases
  if ($entity_type->id() === 'oc_case') {
    $fields['actors_involved'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Involved Parties'))
      ->setDescription(t('People involved in this case. To add one, start typing their name.'))
      ->setSetting('target_type', 'oc_actor')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', [
        'label' => 'above',
        'type' => 'entity_reference_autocomplete',
        'weight' => -2,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
      ])
      ->setDefaultValueCallback('opencase_defaults_actors_involved_callback')
      ->setRequired(TRUE);
  }
  return $fields;
}

/**
 * When creating a case, it sets the first involved party to the actor
 * id from the URL, and the second to the author's linked actor 
 * (if it exists and is different)
 */
function opencase_defaults_actors_involved_callback() {
  $author_linked_actor_id = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->get('field_linked_opencase_actor')->target_id;
  $currently_viewed_actor_id = \Drupal::request()->query->get('actor_id');
  return array_unique([$currently_viewed_actor_id, $author_linked_actor_id]);
}

/**
 * Implements hook_form_ID_alter
 */
function opencase_defaults_form_oc_case_type_add_form_alter(&$form, $form_state) {
  $widget = new EntityTypeRelationsWidget();
  $widget->setup($form);
}


/**
 * Implements hook_form_ID_alter
 */
function opencase_defaults_form_oc_case_type_edit_form_alter(&$form, $form_state) {
  $widget = new EntityTypeRelationsWidget();
  $widget->setup($form);
  $widget->populate($form);
}