<?php

/**
 * @file
 * Module file for social_lets_connect_usage.
 */

use Drupal\Component\Utility\Crypt;

/**
 * Cron for sharing usage data.
 */
function social_lets_connect_usage_cron() {

  $current_time = time();
  $last_send = \Drupal::state()
    ->get('social_lets_connect_usage.last_send', 0);
  $times_send = \Drupal::state()
    ->get('social_lets_connect_usage.times_send', 0);

  $settings = \Drupal::config('social_lets_connect_usage.settings');
  if ($settings->get('usage_data_enabled')) {

    $refresh_interval = $settings->get('refresh_interval');

    if (($current_time - $last_send) >= $refresh_interval) {
      /** @var \Drupal\social_lets_connect_usage\Plugin\ShareUsageDataPluginManager $plugin_manager */
      $plugin_manager = \Drupal::service('plugin.manager.share_usage_data_plugin');
      $plugin_definitions = $plugin_manager->getDefinitions();
      $usage_data = [];
      foreach ($plugin_definitions as $plugin_id => $plugin_definition) {
        $instance = $plugin_manager->createInstance($plugin_id);
        $usage_data[$plugin_id] = FALSE;
        if ($instance->enabled()) {
          $usage_data[$plugin_id] = $instance->getValue();
        }
      }

      global $base_url;
      $private_key = \Drupal::service('private_key');
      $site_key = Crypt::hmacBase64($base_url, $private_key->get());

      $send_data = [];
      $send_data['site_key'] = $site_key;
      $send_data['send_info'] = [
        'last_send' => $last_send,
        'times_send' => $times_send,
        'current_time' => $current_time,
      ];
      $send_data['usage_data'] = $usage_data;

      $queue = \Drupal::queue('send_usage_data');
      $queue->createItem($send_data);

      // Update last run.
      \Drupal::state()
        ->set('social_lets_connect_usage.last_send', $current_time);
      $times_send++;
      \Drupal::state()
        ->set('social_lets_connect_usage.times_send', $times_send);
    }

  }

}
