<?php

namespace Drupal\materio_graphql\Plugin\GraphQL\DataProducer;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\materio_graphql\GraphQL\Response\MateriauResponse;
use Drupal\node\Entity\Node;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Creates a new materiau entity.
 *
 * @DataProducer(
 *   id = "create_materiau",
 *   name = @Translation("Create Materiau"),
 *   description = @Translation("Creates a new materiau."),
 *   produces = @ContextDefinition("any",
 *     label = @Translation("Materiau")
 *   ),
 *   consumes = {
 *     "data" = @ContextDefinition("any",
 *       label = @Translation("Materiau data")
 *     )
 *   }
 * )
 */
class CreateMateriau extends DataProducerPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

  /**
   * CreateMateriau constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(array $configuration, string $plugin_id, array $plugin_definition, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->currentUser = $current_user;
  }

  /**
   * Creates an materiau.
   *
   * @param array $data
   *   The submitted values for the materiau.
   *
   * @return \Drupal\graphql_composable\GraphQL\Response\MateriauResponse
   *   The newly created materiau.
   *
   * @throws \Exception
   */
  public function resolve(array $data) {
    $response = new MateriauResponse();
    if ($this->currentUser->hasPermission("create materiau content")) {
      $values = [
        'type' => 'materiau',
        'title' => $data['title'],
        'body' => $data['description'],
      ];
      $node = Node::create($values);
      $node->save();
      $response->setMateriau($node);
    }
    else {
      $response->addViolation(
        $this->t('You do not have permissions to create materiaus.')
      );
    }
    return $response;
  }

}
