<?php

namespace Drupal\nodehive_core\Form;

use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a add form for a user.
 */
class UserAddForm extends UserAddEditBaseForm {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'nodehive_core_user_add_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $entity = $this->entityTypeManager()
      ->getStorage('user')
      ->create();

    $form['user'] = $this->getBaseUserForm($entity);

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    if (isset($values['pass'])) {
      if ($values['password'] != $values['confirm_password']) {
        $form_state->setErrorByName(
          'password',
          $this->t(
            "Passwords does not match."
          ),
        );

        return FALSE;
      }
    }

    if ($values['password'] != $values['confirm_password']) {
      $form_state->setErrorByName(
        'password',
        $this->t(
          "Passwords does not match."
        ),
      );

      return FALSE;
    }

    $mail = $values['mail'];
    $user = $this->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
        'mail' => $mail,
      ]);

    if ($user) {
      $form_state->setErrorByName(
        'mail',
        $this->t(
          "User with this email address already exist."
        ),
      );

      return FALSE;
    }

    $name = $values['name'];
    $user = $this->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
        'name' => $name,
      ]);

    if ($user) {
      $form_state->setErrorByName(
        'name',
        $this->t(
          "User with this username already exist."
        ),
      );

      return FALSE;
    }

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->createNewUser($form_state);
  }

  /**
   * Create a new Drupal user and assign it to a space.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   */
  public function createNewUser(FormStateInterface $form_state) {
    $values = $form_state->getValues();

    /** @var \Drupal\user\UserInterface $user */
    $user = $this->entityTypeManager()
      ->getStorage('user')
      ->create([
        'name' => $values['name'],
        'mail' => $values['mail'],
        'status' => $values['status'],
      ]);

    $user->setPassword($values['password']);
    $user->enforceIsNew(TRUE);

    $user->set('timezone', $values['timezone']);
    $user->set('user_picture', $values['picture']);
    $user->set('preferred_langcode', $values['language']);

    foreach (array_filter($values['roles']) as $rid => $label) {
      $user->addRole($rid);
    }

    $user->save();

    if ($values['notify']) {
      _user_mail_notify('register_no_approval_required', $user);
    }

    // Set spaces.
    foreach ($values['spaces'] as $id) {
      $space_entity = $this->entityTypeManager()
        ->getStorage('nodehive_space')
        ->load($id);

      if (!$space_entity || !$space_entity->editors) {
        continue;
      }

      $saved_users_values = $space_entity->editors->getValue();
      $saved_users = [];
      foreach ($saved_users_values as $item) {
        $saved_users[$item['target_id']] = $item['target_id'];
      }

      $saved_users[$user->id()] = $user->id();

      $space_entity->editors = $saved_users;
      $space_entity->save();
    }

    $this->messenger()->addMessage(
      $this->t(
        "User @username has been created successfully.",
        [
          '@username' => $user->getAccountName(),
        ]
      ),
    );
  }

}
