<?php

namespace Drupal\materio_flag\Commands;


use Drush\Commands\DrushCommands;
use Drupal\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\flag_lists\FlagListsService;
use Drupal\Core\Session\AccountProxyInterface;

class MaterioFlagCleaning extends DrushCommands {

  /**
   * @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;
  }

  /**
   * Try to recreate missing related flags.
   *
   * @command materio_flag:recreate_missing_related_flags
   * @aliases mf-rmrf
   */
  public function recreate_missing_related_flags() {
    $database = \Drupal::database();

    $this->output()->writeln("");
    $this->output()->writeln("Missing related flag Flagging collection cleaning");
    $fcfd_query = $database->select('flagging_collection_field_data', 'fcfd')
      ->fields('fcfd', ['id', 'relatedflag']);

    $fcfd_result = $fcfd_query->execute();
    $this->output()->writeln($fcfd_query->countQuery()->execute()->fetchField() . " flagging_collections");

    $fc_missing_relatedflag = 0;
    foreach ($fcfd_result as $fc) {
      $flag_query = $database->select('config', 'c')
        ->condition('c.name', 'flag.flag.' . $fc->relatedflag)
        ->fields('c', ['name']);
      // $conf_result = $flag_query->execute();
      $count = $flag_query->countQuery()->execute()->fetchField();
      if(!$count){
        $fc_missing_relatedflag ++;
        $flagList = $this->flagListsService->getFlaggingCollectionById($fc->id);
        $this->output()->writeln(' flagging_collection ' . $flagList->getName() . ' ('. $fc->id . ') has ' . $count . " relatedflag");
        $flagList->save();
      }
    }
    $this->output()->writeln($fc_missing_relatedflag .' flagging_collection with missing related_flag');

  }

  /**
   * Clean multiple flag list for one related flag.
   *
   * @command materio_flag:clean_duplicates_related_flags
   * @aliases mf-cdrf
   */
  public function clean_duplicates_related_flags() {
    // searching for duplicates relatedflags
    $database = \Drupal::database();

    $this->output()->writeln("");
    $this->output()->writeln("Duplicate relatedflag flagging_collection cleaning");
    $dup_query = $database->select('flagging_collection_field_data', 'fcfd')
      ->fields('fcfd', ['relatedflag'])
      ->groupBy('fcfd.relatedflag')
      ->having('COUNT(*) > 1');
    $dup_query->addExpression('COUNT(*)', 'count');

    // $results = $query->execute()->fetchAll();

    $dup_result = $dup_query->execute();
    $this->output()->writeln($dup_query->countQuery()->execute()->fetchField() . " duplicate related flags");

    foreach ($dup_result as $dup){
      // $this->output()->writeln($dup->relatedflag . " is dup");
      $fcfd_query = $database->select('flagging_collection_field_data', 'fcfd')
        ->condition('fcfd.relatedflag', $dup->relatedflag)
        ->fields('fcfd', ['id', 'relatedflag']);
      $fcfd_result = $fcfd_query->execute();
      $count = $fcfd_query->countQuery()->execute()->fetchField();
      
      $this->output()->writeln($dup->relatedflag . ' relatedflag has ' . $count . ' flagging collection');
      
      foreach ($fcfd_result as $fc) {
        $flagList = $this->flagListsService->getFlaggingCollectionById($fc->id);
        $flagList->save();
        // delete_flagingcollection($fc, $database, $delete_all ? true : $delete_dups);
      }

    }
  }
}





