<?php

namespace Drupal\edlp_studio\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\User\UserDataInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

use Drupal\edlp_studio\Entity\Chutier;

/**
 * Class ChutierController.
 */
class ChutierController extends ControllerBase {

  protected $user;
  protected $userdata;

  /**
   * Class constructor.
   */
  public function __construct(AccountInterface $account, UserDataInterface $userdata) {
    $this->user = $account;
    $this->userdata = $userdata;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
      // Load the service required to construct this class.
      $container->get('current_user'),
      $container->get('user.data')
    );
  }


  /**
   * AdddContent.
   *
   * @return json
   *   Return status.
   */
  public function AddRemoveContent($action, $id, $cid) {
    $this->error_message = null;
    $status = 'ok';
    // get current user :
    // done by DependencyInjection of AccountInterface

    // TODO: use the send chutier instead of default
    // check if default chutier exists ? yes use it : no create and use it.
    $this->checkChutier();
    // dpm($this->chutier);

    // check if $id exists, is a document, and does not already exist in chutier
    switch($action){
      case 'add':
        $this->validateNewDoc($id);
        if(!$this->error_message){
          // add $id to documents field
          $this->addNewDoc($id);
          $message = t('Node @id added to chutier.', array('@id'=>$id));
        }else{
          $status = "error";
        }
        break;
      case 'remove':
        $this->removeDoc($id);
        $message = t('Node @id removed to chutier.', array('@id'=>$id));
        break;
    }

    $url = Chutier::getActionsUrl($id, $this->user->id());
    $new_link_build = array(
      '#title' => t("Chutier."),
      '#type' => 'link',
      '#url' => $url,
      '#options'=>array(
        'attributes' => array(
          'data-drupal-link-system-path' => $url->getInternalPath()
        )
      )
    );
    $new_link = render($new_link_build);

    if($status == 'error'){
      $message = $this->error_message;
    }

    // JSON
    $response = new JsonResponse();
    $data = array(
      'status' => $status,
      'message' => $message,
      'new_link' => $new_link,
      'action_done' => $action,
    );
    $response->setData($data);
    return $response;

    // classic html
    // return array(
    //   '#markup'=>'Status : ' . $status . ' | Message : ' . $message,
    // );
  }

  private function addNewDoc($id){
    $this->chutier->documents->appendItem($id);
    $this->chutier->save();
  }

  private function removeDoc($id){
    $values = array_column($this->chutier->documents->getValue(), 'target_id');
    $index = array_search($id,$values);
    $this->chutier->documents->removeItem($index);
    $this->chutier->save();
  }

  private function validateNewDoc($id){
    $node = entity_load('node', $id);
    if($node){
      // TODO: get node bundle by settings (@see readme)
      if($node->getType() == 'enregistrement'){
        $docs = array_column($this->chutier->documents->getValue(), 'target_id');
        if( in_array($id, $docs) ){
          $this->error_message = t("Node '@title'(@id) already exists in chutier '@name'(@cid)", array(
            '@title'=>$node->getTitle(),
            '@id'=>$id,
            '@name' => $this->chutier->getName(),
            '@cid' => $this->chutier->id())
          );
        }
      }else{
        $this->error_message = t("Node @title (@id) is not an Enregistrement (@type)", array(
          '@title'=>$node->getTitle(),
          '@id'=>$id,
          '@type' => $node->getType())
        );
      }
    }else{
      $this->error_message = t("Node @id does not exists", array('@id'=>$id));
    }
  }

  private function checkChutier(){
    $default_chutier_id = $this->userdata->get('edlp_studio', $this->user->id(), 'default_chutier');
    // dpm($this->default_chutier_id);
    $this->chutier = entity_load('chutier', $default_chutier_id);
    // if default chutier does not exists, create, save and record it
    if(!$this->chutier){
      $this->createDefaultChutier();
    }
  }

  private function createDefaultChutier(){
    // dpm('createDefaultChutier');
    $this->createChutier();
    $this->userdata->set('edlp_studio', $this->user->id(), 'default_chutier', $this->chutier->id());
  }

  public function createChutier(){
    $chutier = array(
      'id' => NULL,
      'uid' => $this->user->id(),
      'status' => TRUE,
      'name' => t('Default'),
    );
    $this->chutier = entity_create('chutier', $chutier);
    $this->chutier->save();
  }

}
