<?php

namespace Drupal\collector_systems\Plugin\QueueWorker;

use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\collector_systems\ImagesSyncManager;
use Drupal\collector_systems\DataSyncManager;
/**
 * @QueueWorker(
 *   id = "collector_systems_sync_queue_worker",
 *   title = @Translation("Collector Systems Sync Queue Worker"),
 *   cron = {"time" = 180}
 * )
 */
class SyncQueueWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  protected $syncService;
  protected $logger;
  protected $imagesSyncManager;
  protected $dataSyncManager;

  public function __construct(
    array $configuration, 
    $plugin_id,
    $plugin_definition,
    LoggerChannelFactoryInterface $logger_factory,
    ImagesSyncManager $imagesSyncManager,
    DataSyncManager $dataSyncManager
  ){
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->logger = $logger_factory->get('collector_systems');
    $this->imagesSyncManager = $imagesSyncManager;
    $this->dataSyncManager = $dataSyncManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('logger.factory'),
      $container->get('collector_systems.images_sync_manager'),
      $container->get('collector_systems.data_sync_manager')
    );
  }

  public function processItem($item) {
    $config_collector_systems = \Drupal::config('collector_systems.settings');
    $save_images_on_automatic_sync_to = $config_collector_systems->get('save_images_on_automatic_sync_to') ?? 'save_to_directory';

    $queue_type = $item['queue_type'];
    // Process each item in the queue.
    $this->logger->info('Processing item: ' . print_r($item, TRUE));

    if ($queue_type == 'dataset') {
      // hardcoded update_dataset because the queue is for automatic sync and we only update dataset in automatic sync.
      $btn_action = 'update_dataset';
      $this->dataSyncManager->processItem($item['data'], $btn_action);
    }
    elseif ($queue_type == 'object_images'){
      $this->imagesSyncManager->processItem_ObjectImages($item['data'], $save_images_on_automatic_sync_to);
    }
    elseif ($queue_type == 'other_images'){
      $this->imagesSyncManager->processItem_OtherImages($item['data'], $save_images_on_automatic_sync_to);
    }

     // Check if more items are left in the queue
    $queue = \Drupal::queue('collector_systems_sync_queue_worker');
    $remaining_items = $queue->numberOfItems();
    if ($remaining_items === 0) {
      // automatic sync completed. store the info in the database table.
      collector_systems_update_CSSynced_table('data_and_images', 'automatic', false,  true);
    }
  }
}
