<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OCA\Social\Command;

use OC\Core\Command\Base;
use OCA\Social\AP;
use OCA\Social\Exceptions\ItemUnknownException;
use OCA\Social\Exceptions\RedundancyLimitException;
use OCA\Social\Exceptions\SocialAppConfigException;
use OCA\Social\Model\ActivityPub\Actor\Person;
use OCA\Social\Model\ActivityPub\Stream;
use OCA\Social\Tools\Exceptions\CacheItemNotFoundException;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\OutputInterface;

class ExtendedBase extends Base {
	protected ?OutputInterface $output = null;
	protected bool $asJson = false;
	protected int $crop = 0;

	protected function outputActor(Person $actor): void {
		if ($this->asJson) {
			$this->output->writeln(json_encode($actor, JSON_PRETTY_PRINT));
		}

		$this->output->writeln('<info>Account</info>: ' . $actor->getAccount());
		$this->output->writeln('<info>Id</info>: ' . $actor->getId());
		$this->output->writeln('');
	}


	/**
	 * @param Stream[] $streams
	 */
	protected function outputStreams(array $streams) {
		if ($this->asJson) {
			$this->output->writeln(json_encode($streams, JSON_PRETTY_PRINT));
			return;
		}

		$table = new Table($this->output);
		$table->setHeaders(['Nid', 'Id', 'Source', 'Type', 'Author', 'Content']);
		$table->render();

		foreach ($streams as $item) {
			$objectId = $item->getObjectId();
			$cache = $item->getCache();
			$content = '';
			$author = '';
			if ($objectId !== '' && $cache->hasItem($objectId)) {
				try {
					$cachedObject = $cache->getItem($objectId)
										  ->getObject();

					/** @var Stream $cachedItem */
					$cachedItem = AP::$activityPub->getItemFromData($cachedObject);
					$content = $cachedItem->getContent();
					$author = $cachedItem->getActor()
										 ->getAccount();
				} catch (CacheItemNotFoundException $e) {
				} catch (ItemUnknownException $e) {
				} catch (RedundancyLimitException $e) {
				} catch (SocialAppConfigException $e) {
				}
			} else {
				$content = $item->getContent();
				$author = $item->getActor()
							   ->getAccount();
			}

			$content = ($this->crop) ? substr($content, 0, $this->crop) : $content;

			$table->appendRow(
				[
					$item->getNid(),
					'<comment>' . $item->getId() . '</comment>',
					'<info>' . $item->getActor()
									->getAccount() . '</info>',
					$item->getType(),
					'<info>' . $author . '</info>',
					$content,
				]
			);
		}
	}


	/**
	 * @param Stream $stream
	 */
	protected function outputStream(Stream $stream) {
		$actor = $stream->getActor();
		$this->output->writeln('id: <comment>' . $stream->getId() . '</comment>');
		$this->output->writeln(
			'author: <comment>' . $actor->getAccount() . '</comment>'
		);
		$this->output->writeln('type: <info>' . $stream->getType() . '</info>');
	}
}
