<?php

/**
 * @file
 * Contains opencase_no_cases.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_help().
 */
function opencase_no_cases_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the opencase_no_cases module.
    case 'help.page.opencase_no_cases':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Enable EITHER this OR &quot;OpenCase Cases&quot;. This one links activities directly to people, which is simpler and therefore what some orgs prefer.') . '</p>';
      return $output;

    default:
  }
}

function opencase_no_cases_entity_base_field_info($entity_type) {
  if ($entity_type->id() === 'oc_activity') {
    $fields = array();
    $fields['actors_involved'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Participants'))
      ->setDescription(t('People involved in this activity. To add one, start typing their name.'))
      ->setSetting('target_type', 'oc_actor')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', [
        'label' => 'above',
        'type' => 'hidden',
        'weight' => -100,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -100,
      ])
      ->setDefaultValueCallback('opencase_no_cases_actors_involved_callback')
      ->setRequired(TRUE);
  }
  return $fields;
}

/**
 * When creating an activity, 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_no_cases_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]);
}

/**
 * Implementation of hook_form_alter()
 * When deleting an activity go back to the page of the first listed involved party (as this is likely to be the "target" of the activity).
 */
function opencase_form_alter(&$form, &$form_state, $form_id) {
  if (preg_match('/oc_actor_.*_delete_form/', $form_id) or (preg_match('/oc_organisation_.*_delete_form/', $form_id))) {
    $form['actions']['submit']['#submit'][] = '_opencase_no_cases_redirect_to_home';
    $form['actions']['cancel']['#url'] = $form_state->getFormObject()->getEntity()->toUrl();
  }
  if (preg_match('/oc_activity_.*_delete_form/', $form_id)) {
    $form['actions']['submit']['#submit'][] = '_opencase_no_cases_delete_activity_redirect';
    $form['actions']['cancel']['#url'] = $form_state->getFormObject()->getEntity()->toUrl();
  }
}

function _opencase_no_cases_redirect_to_home($form, &$form_state) {
  $form_state->setRedirect('<front>'); 
}
function _opencase_no_cases_delete_activity_redirect($form, &$form_state) {
  $actor_id = $form_state->getFormObject()->getEntity()->actors_involved[0]->target_id;
  $form_state->setRedirect('entity.oc_actor.canonical', ['oc_actor' => $actor_id]);
}
/**
 * Implements hook_uninstall().
 */
function opencase_no_cases_uninstall() {
  $dir = new DirectoryIterator(dirname(__FILE__) . "/config/install");
  $configs = [];
  foreach ($dir as $fileinfo) {
      if (!$fileinfo->isDot()) {
          $configs[] = str_replace('.yml', '', $fileinfo->getFilename());
      }
  }
  foreach($configs as $config) {
    Drupal::configFactory()->getEditable($config)->delete();
  }
}