<?php

/**
 * @file
 * Install/update/uninstall hooks.
 */

use Drupal\Core\Url;

/**
 * Implements hook_requirements().
 */
function feeds_requirements($phase) {
  $requirements = [];
  if ($phase == 'install') {
    // Check if laminas/laminas-feed has been installed.
    if (!class_exists('\Laminas\Feed\Reader\Reader')) {
      // Check if the Ludwig module has been installed. If so, the packages
      // aren't downloaded yet.
      if (\Drupal::moduleHandler()->moduleExists('ludwig')) {
        $requirements['laminas-feed'] = [
          'description' => t('Feeds requires the library "@library". It can be downloaded by the Ludwig module, which you appear to have installed. Go to <a href=":link">Packages list</a> to install the missing libraries.', [
            '@library' => 'laminas/laminas-feed',
            ':link' => Url::fromUri('internal:/admin/reports/packages')->toString(),
          ]),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      // The Ludwig module has not been installed, so provide instructions of
      // how to obtain the library.
      else {
        $requirements['laminas-feed'] = [
          'description' => t('Feeds requires the library "@library". You can install it with Composer or by using the Ludwig module.', [
            '@library' => 'laminas/laminas-feed',
          ]),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
    }
  }

  return $requirements;
}

/**
 * Implements hook_install().
 */
function feeds_install() {
  $messenger = \Drupal::messenger();
  $messenger->addStatus(t('To configure feeds, start by adding a <a href=":feed_type_add_url">feed type</a>. For more information <a target="feeds-guide" href=":guide_url">read the guide</a>.', [
    ':feed_type_add_url' => Url::fromUri('internal:/admin/structure/feeds/add')->toString(),
    ':guide_url' => 'https://www.drupal.org/docs/8/modules/feeds/creating-and-editing-import-feeds',
  ]));
}

/**
 * Implements hook_uninstall().
 */
function feeds_uninstall() {
  $database = \Drupal::database();

  // Delete Feeds states.
  if ($database->schema()->tableExists('key_value')) {
    $collections = $database->select('key_value')
      ->fields('key_value', ['collection'])
      ->condition('collection', 'feeds_feed.%', 'LIKE')
      ->groupBy('collection')
      ->execute();

    foreach ($collections as $collection_record) {
      \Drupal::keyValue($collection_record->collection)->deleteAll();
    }
  }

  // Delete all Feeds queues.
  if ($database->schema()->tableExists('queue')) {
    $queues = $database->select('queue')
      ->fields('queue', ['name'])
      ->condition('name', 'feeds_feed_refresh:%', 'LIKE')
      ->groupBy('name')
      ->execute();

    foreach ($queues as $queue_record) {
      $queue = \Drupal::queue($queue_record->name);
      if ($queue) {
        $queue->deleteQueue();
      }
    }
  }
}

/**
 * Implements hook_schema().
 */
function feeds_schema() {
  $schema['feeds_clean_list'] = [
    'description' => 'Keeps a list of items to clean after the process stage.',
    'fields' => [
      'feed_id' => [
        'description' => 'The ID of the feed.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ],
      'entity_id' => [
        'description' => 'The ID of the entity to clean.',
        'type' => 'varchar_ascii',
        'length' => 255,
        'not null' => TRUE,
      ],
    ],
    'primary key' => ['feed_id', 'entity_id'],
  ];

  return $schema;
}

/**
 * Resave all feed types to recalculate config dependencies.
 */
function feeds_update_8001() {
  foreach (\Drupal::entityTypeManager()->getStorage('feeds_feed_type')->loadMultiple() as $feed_type) {
    $feed_type->save();
  }
}

/**
 * Installs new table 'feeds_clean_list'.
 */
function feeds_update_8002() {
  $schema = \Drupal::database()->schema();
  if (!$schema->tableExists('feeds_clean_list')) {
    // Add feeds_clean_list table.
    $schema->createTable('feeds_clean_list', [
      'description' => 'Keeps a list of items to clean after the process stage.',
      'fields' => [
        'feed_id' => [
          'description' => 'The ID of the feed.',
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ],
        'entity_id' => [
          'description' => 'The ID of the entity to clean.',
          'type' => 'varchar_ascii',
          'length' => 255,
          'not null' => TRUE,
        ],
      ],
    ]);
  }
}

/**
 * Adds a primary key to {feeds_clean_list} table.
 */
function feeds_update_8003() {
  $schema = \Drupal::database()->schema();
  if ($schema->tableExists('feeds_clean_list')) {
    $schema->dropPrimaryKey('feeds_clean_list');
    $schema->addPrimaryKey('feeds_clean_list', ['feed_id', 'entity_id']);
  }
}

/**
 * Flush all caches to make plugin type "FeedsCustomSource" available.
 */
function feeds_update_8004() {
  drupal_flush_all_caches();
}

/**
 * Set the default lock timeout for Feeds imports.
 */
function feeds_update_8005() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('feeds.settings');
  $config->set('lock_timeout', 43200);
  $config->save(TRUE);
}

/**
 * Flush all caches to make the service "feeds.lock" available.
 */
function feeds_update_8006() {
  drupal_flush_all_caches();
}

/**
 * Ensure entity_id in feeds_clean_list is a string.
 */
function feeds_update_8007() {
  $schema = \Drupal::database()->schema();
  if ($schema->tableExists('feeds_clean_list')) {
    $new = [
      'description' => 'The ID of the entity to clean.',
      'type' => 'varchar_ascii',
      'length' => 255,
      'not null' => TRUE,
    ];
    $schema->dropPrimaryKey('feeds_clean_list');
    $schema->changeField('feeds_clean_list', 'entity_id', 'entity_id', $new);
    $schema->addPrimaryKey('feeds_clean_list', ['feed_id', 'entity_id']);
  }
}
