<?php

namespace Drupal\materio_flag\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\flag_lists\FlagListsService;
use Drupal\flag_lists\Entity\FlaggingCollection;
use Drupal\flag_lists\Controller\ActionLinkController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
 * Class AjaxHomeController.
 */
class MaterioFlagController extends ControllerBase {


  /*
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * @var \Drupal\flag_lists\FlagListsService
   */
  protected $flagListsService;

  /**
   * @var \Drupal\user\User
   */
  protected $user;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('flaglists'),
      $container->get('current_user')
    );
  }

  /**
   * Constructs a new MaterioFlagController object.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, FlagListsService $flag_lists_service, AccountProxyInterface $account) {
    $this->entityTypeManager = $entity_type_manager;
    $this->flagListsService = $flag_lists_service;
    $this->user = $account;
  }

  /**
   * Hello.
   *
   * @return string
   *   Return Hello string.
   */
  public function getUsersFlaggingCollections() {

    $colls = $this->flagListsService->getUsersFlaggingCollections();

    $data = [];
    foreach ($colls as $id => $collection) {
      $flag_id = $collection->getRelatedFlag()->id();

      // get the items
      $itemsids = $this->flagListsService->getFlagListItemIds($flag_id,$id);
      $items = [];
      foreach ($this->flagListsService->getFlagListItems($itemsids) as $id => $item) {
        // $items[] = array(
        //   'id' => $id,
        //   'name' => $item->getName(),
        //   'connected_entity_id' => $item->getConnectedEntityId(),
        // );
        $items[] = (int)$item->getConnectedEntityId();
      }
      // $items_uuids = [];
      // foreach ($items as $nid) {
      //   $node = $this->entityTypeManager->getStorage('node')->load($nid);
      //   $items_uuids[] = $node->uuid();
      // }

      $data[$collection->id()] = array(
        "id" => $collection->id(),
        "name" => $collection->getName(),
        "flag_id" => $flag_id,
        "items" => $items
        // "items_uuids" => $items_uuids
      );
    }

    return new JsonResponse($data);
  }

  public function createUserFlaggingCollection(Request $request) {
    // dpm($request);
    $post_data = json_decode( $request->getContent(),TRUE);
    $name = $post_data['name'];

    $newFlagColl = FlaggingCollection::Create([
      'type' => 'flagging_collection_type',
      'name' => $name,
      'user_id' => $this->user->id(),
      'templateflag' => 'dossier'
    ]);

    $newFlagColl->save();

    $data = [
      'status' => $newFlagColl->get('status')->value,
      'id' => $newFlagColl->id(),
      'name' => $newFlagColl->getName(),
      'newflagcoll_toarray' => $newFlagColl->toArray()
    ];
    return new JsonResponse($data);
  }

  public function deleteUserFlaggingCollection(Request $request) {
    // dpm($request);
    $post_data = json_decode( $request->getContent(),TRUE);
    $flagcollid = $post_data['flagcollid'];

    $flagcoll = $this->flagListsService->getFlaggingCollectionById($flagcollid);

    $relatedflag = $flagcoll->getRelatedFlag();

    // flaglistitems are not deleted with the flagcoll
    $itemsids = $this->flagListsService->getFlagListItemIds($relatedflag->id(),$flagcoll->id());
    foreach ($this->flagListsService->getFlagListItems($itemsids) as $item) {
      $item->delete();
    }

    // TODO: warning, sometimes relatedFlag deos not exists
    // $flag = $flagcoll->getRelatedFlag();

    // finaly delete the flag collection
    $flagcoll->delete();

    $data = [
      // 'result' => $flag,
      'id' => $flagcollid
    ];
    return new JsonResponse($data);
  }

  // public function flag(Request $request) {
  //   // dpm($request);
  //   $post_data = json_decode( $request->getContent(),TRUE);
  //   $flagid = $post_data['flagid'];
  //   $nid = $post_data['nid'];
  //   $flagcollid = $post_data['flagcollid'];
  //
  //   $actionLinkController = new ActionLinkController();
  //   // FlagInterface $flag, $entity_id, $flag_list
  //   $status = $actionLinkController->flag($flagid, $nid, $flagcollid);
  //
  //   // $flagcoll = $this->flagListsService->getFlaggingCollectionById($flagid);
  //   // // dump($flagcoll);
  //   // $flagcoll->delete();
  //   // // TODO: warning, sometimes relatedFlag deos not exists
  //   // // $flag = $flagcoll->getRelatedFlag();
  //
  //   $data = [
  //     'status' => $flag,
  //     'flagid' => $flagid,
  //     'nid' => $nid,
  //     'flagcollid' => $flagcollid
  //   ];
  //   return new JsonResponse($data);
  // }


}
