<?php

/**
 * @file
 * Install, update and uninstall function for the farm_fieldkit module.
 */

use Drupal\consumers\Entity\Consumer;
use Drupal\simple_oauth\Oauth2ScopeInterface;

/**
 * Implements hook_install().
 */
function farm_fieldkit_install() {

  // Check for default role scopes.
  /** @var \Drupal\simple_oauth\Oauth2ScopeProviderInterface $scope_provider */
  $scope_provider = \Drupal::service('simple_oauth.oauth2_scope.provider');
  $scopes = $scope_provider->loadMultiple(['farm_manager', 'farm_worker']);
  $scope_ids = array_map(function (Oauth2ScopeInterface $scope) {
    return $scope->id();
  }, $scopes);

  // Create a consumer for the farmOS Field Kit client.
  $fk_consumer = Consumer::create([
    'label' => 'Field Kit',
    'client_id' => 'fieldkit',
    'access_token_expiration' => 3600,
    'grant_types' => [
      'refresh_token',
      'password',
    ],
    'scopes' => array_values($scope_ids),
    'redirect' => 'https://farmOS.app',
    'allowed_origins' => 'https://farmos.app',
    'secret' => NULL,
    'confidential' => FALSE,
    'third_party' => FALSE,
  ]);
  $fk_consumer->save();
}

/**
 * Implements hook_uninstall().
 */
function farm_fieldkit_uninstall() {

  // Load the fieldkit consumer.
  $consumers = \Drupal::entityTypeManager()->getStorage('consumer')
    ->loadByProperties(['client_id' => 'fieldkit']);

  // If found, delete the consumer.
  if (!empty($consumers)) {
    $client_consumer = reset($consumers);
    $client_consumer->delete();
  }
}
