<?php

namespace Drupal\user_provisioning\ProviderSpecific\Parsers\UserParser;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Entity\EntityInterface;
use Drupal\user_provisioning\Helpers\moProviderSpecificProvisioning;
use Drupal\user_provisioning\Helpers\moUserProvisioningLogger;
use Drupal\user_provisioning\ProviderSpecific\Parsers\moResourceParserInterface;

/**
 *
 */
class moUserAzureParser implements moResourceParserInterface {

  private moUserProvisioningLogger $mo_logger;
  private ImmutableConfig $config;
  private Config $config_factory;

  /**
   *
   */
  public function __construct() {
    $this->mo_logger = new moUserProvisioningLogger();
    $this->config = \Drupal::config('azure_ad.settings');
    $this->config_factory = \Drupal::configFactory()->getEditable('azure_ad.settings');
  }

  /**
   * {@inheritDoc}
   */
  public function search($resource_id): string {
      $this->mo_logger->addLog("Creating search request parameter.", __LINE__, __FUNCTION__, __FILE__);
      return $resource_id;
  }

  /**
   * {@inheritDoc}
   */
  public function get($resource_id) {
    // @todo Implement get() method.
  }

  /**
   * {@inheritDoc}
   */
  public function post(EntityInterface $entity) {

    $email_attr = $this->config->get('azure_ad_mapping_mail_attr');
    $username_attr = $this->config->get('azure_ad_mapping_username_attr');

    if (isset($email_attr)) {
      if ($email_attr == 'uid') {
        $mailNickname = $entity->id();
      }
      else {
        $mailNickname = $entity->get($email_attr)->value;
      }
    }

    if (isset($username_attr)) {
      if ($username_attr == 'uid') {
        $username = $entity->id();
      }
      else {
        $username = $entity->get($username_attr)->value;
      }
    }

    if ((\Drupal::service('email.validator')->isValid($mailNickname))) {
      $mailNickname = explode('@', $mailNickname)[0];
    }

    if ((\Drupal::service('email.validator')->isValid($username))) {
      $username = explode('@', $username)[0];
    }

    $drupal_username = $entity->getDisplayName();
    $user_info = $this->config->get('mo_azure_ad_' . $drupal_username . '_dependency');
    $this->config_factory->clear('mo_azure_ad_' . $drupal_username . '_dependency')->save();
    $prov_specific_provisioning = new moProviderSpecificProvisioning();

    $azure_password = isset($user_info) && !empty($user_info) ? $prov_specific_provisioning->decrypt_data($user_info, $drupal_username) : 'xWwvJ]6NMw+bWH-d';

    $userObject = '{
             "accountEnabled":true,
             "passwordProfile" : {
             "password": "' . $azure_password . '",
             "forceChangePasswordNextSignIn": true
             },
             "mailNickname": "' . $mailNickname . '",
            "passwordPolicies": "DisablePasswordExpiration"
        }';

    $userObject = Json::decode($userObject);
    $userObject['userPrincipalName'] = $username . '@' . $this->config->get('mo_azure_tenant_name');
    $userObject['displayName'] = $username;

      // Log the final user object being returned
      $this->mo_logger->addLog('Final user object: ' . print_r($userObject, TRUE), __LINE__, __FUNCTION__, __FILE__);
      $this->mo_logger->addFormattedLog(['userObject' => $userObject,], __LINE__, __FUNCTION__, __FILE__, 'Final User Object created.');
    return $userObject;
  }

  /**
   * {@inheritDoc}
   */
  public function put(array $resource) {
    // @todo Implement put() method.
  }

  /**
   * {@inheritDoc}
   */
  public function patch(array $resource) {
    // @todo Implement patch() method.
  }

  /**
   * {@inheritDoc}
   */
  public function delete(array $resource) {
    // @todo Implement delete() method.
  }

  /**
   *
   */
  public function deactivate(EntityInterface $entity) {
    // @todo Implement deactivate() method.
  }

}
