<?php

namespace JetBackup\Ajax\Calls;

if (!defined( '__JETBACKUP__')) die('Direct access is not allowed');

use JetBackup\Ajax\ListRecord;
use JetBackup\CLI\CLI;
use JetBackup\Data\Engine;
use JetBackup\Exception\AjaxException;
use JetBackup\Exception\DBException;
use JetBackup\Exception\JetBackupLinuxException;
use JetBackup\Factory;
use JetBackup\JetBackup;
use JetBackup\JetBackupLinux\JetBackupLinux;
use JetBackup\Queue\Queue;
use JetBackup\Queue\QueueItem;
use JetBackup\SocketAPI\Exception\SocketAPIException;
use JetBackup\UserInput\UserInput;
use SleekDB\Exceptions\InvalidArgumentException;
use SleekDB\Exceptions\IOException;

class ListQueueItems extends ListRecord {

	public function getType():int { return $this->getUserInput(QueueItem::TYPE, 0, UserInput::UINT); }

	/**
	 * @throws DBException
	 * @throws AjaxException
	 * @throws SocketAPIException
	 * @throws IOException
	 * @throws InvalidArgumentException
	 */
	public function execute(): void {
		
		$query = QueueItem::query();
		
		if($this->getType()) $query->where([QueueItem::TYPE, '=', $this->getType()]);
		if($filter = $this->getFilter()) $query->search(['progress.message'], $filter);

		$output = $this->isCLI() ? [] : [ 'items' => [], 'total' => count($query->getQuery()->fetch()) ];

		if($this->getLimit()) $query->limit($this->getLimit());
		if($this->getSkip()) $query->skip($this->getSkip());
		if($this->getSort()) $query->orderBy($this->getSort());
		
		$list = $query->getQuery()->fetch();
		
		foreach($list as $item_details) {
			$item = new QueueItem($item_details[JetBackup::ID_FIELD]);
			if($this->isCLI()) $output[] = $item->getDisplayCLI();
			else $output['items'][] = $item->getDisplay();
		}

		/*
		if(JetBackupLinux::isEnabled()) {
			
			try {
				$groups = JetBackupLinux::listQueueGroups();

				foreach($groups as $group_details) {

					$items = JetBackupLinux::listQueueItems($group_details['_id']);
					
					if(!sizeof($items)) continue;

					// in restore process there is only one queue item for each queue group
					$item_details = $items[0];
					
					if($this->isCLI()) {
						$output[] = [
							'ID'             => $item_details['_id'],
							'Item ID'        => 0,
							'Type'           => 'Restore',
							'Engine'         => Engine::ENGINE_NAMES[Engine::ENGINE_JB],
							'Created'        => CLI::date(strtotime($item_details['created'])),
							'Started'        => $item_details['started'] ? CLI::date(strtotime($item_details['started'])) : 'Never',
							'Ended'          => $item_details['ended'] ? CLI::date(strtotime($item_details['ended'])) : 'Never',
							'Status'         => $item_details['status'],
							'Status Time'    => $item_details['status_time'] ? CLI::date(strtotime($group_details['status_time'])) : 'Never',
							'Log File'       => $item_details['file'],
						];
					} else {
						$output['items'][] = [
							JetBackup::ID_FIELD             => $item_details['_id'],
							QueueItem::UNIQUE_ID                 => '',
							QueueItem::ITEM_ID                   => 0,
							QueueItem::TYPE                      => Queue::QUEUE_TYPE_RESTORE,
							QueueItem::TYPE_NAME                 => Queue::QUEUE_TYPES_NAMES[Queue::QUEUE_TYPE_RESTORE],
							Engine::ENGINE                       => Engine::ENGINE_JB,
							QueueItem::CREATED                   => strtotime($item_details['created']),
							QueueItem::STARTED                   => strtotime($item_details['started']),
							QueueItem::ENDED                     => strtotime($item_details['ended']),
							QueueItem::ITEM_DATA                 => $item_details['data'],
							QueueItem::STATUS                    => $item_details['status'],
							QueueItem::STATUS_NAME               => Queue::QUEUE_STATUS_NAMES[Queue::QUEUE_TYPE_RESTORE][$item_details['status']] ?? '',
							QueueItem::STATUS_TIME               => strtotime($group_details['status_time']),
							QueueItem::PROGRESS                  => $item_details['progress'],
							QueueItem::LOG_FILE                  => $item_details['file'],
							QueueItem::EXEC_TIME                 => gmdate('H:i:s', $item_details['execution_time']),
						];
					}
				}
			} catch(JetBackupLinuxException $e) {
				throw new AjaxException($e->getMessage());
			}
		}
		*/
		
		$this->setResponseData($output);
	}
}