<?php

/**
 * @file
 * Main module file containing hooks.
 */

use \Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\system\MenuInterface;

/**
 * Implements hook_help.
 */
function simple_sitemap_help($route_name, RouteMatchInterface $route_match) {
  return $route_name === 'help.page.simple_sitemap' ?
    check_markup(file_get_contents(dirname(__FILE__) . "/README.md")) : NULL;
}

/**
 * Implements hook_form_alter.
 *
 * Adds sitemap settings to entity types that are supported via plugins.
 */
function simple_sitemap_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $f = \Drupal::service('simple_sitemap.form_helper')->processForm($form_state);
  if (!$f->alteringForm) {
    return;
  }

  $form['simple_sitemap'] = [
    '#type' => 'details',
    '#group' => isset($form['additional_settings']) ? 'additional_settings' : 'advanced',
    '#title' => t('Simple XML sitemap'),
    '#description' => $f->entityCategory == 'instance' ? t('Settings for this entity can be overridden here.') : '',
  ];

  // Attach some js magic to forms.
  // todo: JS not working on comment entity form, hence disabling.
  if ($f->entityTypeId != 'comment' || $f->entityCategory != 'instance') {
    $form['#attached']['library'][] = 'simple_sitemap/form';
  }

  // Only attach fieldset summary js to 'additional settings' vertical tabs.
  if (isset($form['additional_settings'])) {
    $form['#attached']['library'][] = 'simple_sitemap/fieldsetSummaries';
  }

  $f->displayEntitySettings($form['simple_sitemap'])
  // todo: do not show setting when creating new bundle.
    ->displayRegenerateNow($form['simple_sitemap']);

  // Add submission handler.
  if (isset($form['actions']['submit']['#submit'])) {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'simple_sitemap_entity_form_submit';
      }
    }
  }
  // Fix for account page rendering other submit handlers not usable.
  else {
    $form['#submit'][] = 'simple_sitemap_entity_form_submit';
  }
}

/**
 * Form submission handler called in hook_form_alter.
 */
function simple_sitemap_entity_form_submit($form, FormStateInterface &$form_state) {

  $f = \Drupal::service('simple_sitemap.form_helper')->processForm($form_state);

  $values = $form_state->getValues();

  // Fix for values appearing in a sub array on a commerce product entity.
  $values = isset($values['simple_sitemap']) ? $values['simple_sitemap'] : $values;

  // Only make changes in DB if sitemap settings actually changed.
  if ($f->valuesChanged($form, $values)) {
    $generator = \Drupal::service('simple_sitemap.generator');

    switch ($f->entityCategory) {

      case 'bundle':
        $f->bundleName = !empty($f->bundleName) ? $f->bundleName : $f->getFormEntityId();
        $generator->setBundleSettings($f->entityTypeId, $f->bundleName, ['index' => $values['simple_sitemap_index_content'], 'priority' => $values['simple_sitemap_priority']]);
        break;

      case 'instance':
        $f->instanceId = !empty($f->instanceId) ? $f->instanceId : $f->getFormEntityId();
        $generator->setEntityInstanceSettings($f->entityTypeId, $f->instanceId, ['index' => $values['simple_sitemap_index_content'], 'priority' => $values['simple_sitemap_priority']]);
        break;
    }

    // Regenerate sitemaps according to user setting.
    if ($values['simple_sitemap_regenerate_now']) {
      $generator->generateSitemap();
    }
  }
}

/**
 * Implements hook_cron.
 */
function simple_sitemap_cron() {
  $generator = \Drupal::service('simple_sitemap.generator');
  if ($generator->getSetting('cron_generate')) {
    $generator->generateSitemap('backend');
  }
}

/**
 * Implements hook_entity_delete().
 *
 * Removes settings of the removed entity.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 */
function simple_sitemap_entity_delete(EntityInterface $entity) {
  \Drupal::service('simple_sitemap.generator')
    ->removeEntityInstanceSettings($entity->getEntityTypeId(), $entity->id());
}

/**
 * Implements hook_entity_bundle_delete().
 *
 * Removes settings of the removed bundle.
 */
function simple_sitemap_entity_bundle_delete($entity_type_id, $bundle) {
  simple_sitemap_delete_bundle_config($entity_type_id, $bundle);
}

/**
 * Implements hook_menu_delete().
 *
 * Removes settings for the removed menu.
 *
 * @param \Drupal\system\MenuInterface $menu
 */
function simple_sitemap_menu_delete(MenuInterface $menu) {
  simple_sitemap_delete_bundle_config('menu_link_content', $menu->id());
}

/**
 * Helper function used by simple_sitemap_entity_bundle_delete() and
 * simple_sitemap_menu_delete() hooks. This is needed, as menus are technically
 * not bundles.
 *
 * @param string $entity_type_id
 * @param string $bundle
 */
function simple_sitemap_delete_bundle_config($entity_type_id, $bundle) {
  $generator = \Drupal::service('simple_sitemap.generator');
  $deleted_bundle_settings = $generator->getBundleSettings($entity_type_id, $bundle);
  if ($deleted_bundle_settings !== FALSE) {

    // Delete bundle settings.
    \Drupal::service('config.factory')->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle")->delete();

    $message = "You may want to <a href='@url'>regenerate</a> your XML sitemap now.";
    if ($generator->getSetting('cron_generate')) {
      $message .= ' Otherwise the sitemap will be regenerated on the next cron run.';
    }
    drupal_set_message(t($message, ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']));
  }
}
