<?php

namespace Drupal\rest_api_authentication;

/**
 * This class helps the module to write the function.
 */

use Drupal\Core\Url;

/**
 * Has the function which help while authenticate the API requests.
 */
class Utilities {

  /**
   * Generate the random string of the given length.
   */
  public static function generateRandom($length = 30) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $charactersLength = strlen($characters);
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
      $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
  }

  /**
   * This function is used to get the timestamp value.
   */
  public static function getTimestamp() {
    $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/rest/mobile/get-timestamp';
    $fieldString = json_encode([]);

    try {
      $response = \Drupal::httpClient()->post($url, ['headers' => [], 'body' => $fieldString,]);
      $content = $response->getBody()->getContents();

    }
    catch (\Exception $exception) {
      \Drupal::logger('rest_api_authentication')->notice('Error in sending curl Request: @message', ['@message' => $exception->getMessage()]);
      $currentTimeInMillis = round(microtime(TRUE) * 1000);
      return number_format($currentTimeInMillis, 0, '', '');
    }
    if (empty($content)) {
      $currentTimeInMillis = round(microtime(TRUE) * 1000);
      $currentTimeInMillis = number_format($currentTimeInMillis, 0, '', '');
    }
    return empty($content) ? $currentTimeInMillis : $content;
  }

  /**
   * Returns the absolute base URL.
   */
  public static function getBaseUrl() {
    return Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
  }

}
