<?php

declare(strict_types=1);

namespace OCA\RePod\Core\EpisodeAction;

use OCA\GPodderSync\Core\EpisodeAction\EpisodeAction;
use OCA\GPodderSync\Db\EpisodeAction\EpisodeActionRepository;
use OCA\RePod\Service\UserService;

class EpisodeActionReader
{
	public function __construct(
		private EpisodeActionRepository $episodeActionRepository,
		private UserService $userService
	) {}

	public function findByEpisodeUrl(string $episodeUrl): ?EpisodeAction {
		return $this->episodeActionRepository->findByEpisodeUrl($episodeUrl, $this->userService->getUserUID());
	}

	/**
	 * Base: https://github.com/pbek/nextcloud-nextpod/blob/main/lib/Core/EpisodeAction/EpisodeActionExtraData.php#L119.
	 * Specs : https://github.com/Podcast-Standards-Project/PSP-1-Podcast-RSS-Specification/blob/main/README.md.
	 *
	 * @return EpisodeActionExtraData[]
	 * @throws \Exception               if the XML data could not be parsed
	 */
	public function parseRssXml(string $xmlString, ?int $fetchedAtUnix = null): array {
		$episodes = [];
		$xml = new \SimpleXMLElement($xmlString);
		$channel = $xml->channel;
		$podcast = (string) $channel->title;

		// Find episode by url and add data for it
		/** @var \SimpleXMLElement $item */
		foreach ($channel->item as $item) {
			$url = (string) $item->enclosure['url'];
			$type = (string) $item->enclosure['type'];
			$size = (int) $item->enclosure['length'];
			$guid = (string) $item->guid;
			$rawDuration = $this->stringOrNull($item->duration);

			// Get episode action
			$action = $this->episodeActionRepository->findByGuid($guid, $this->userService->getUserUID());

			if ($action) {
				$url = $action->getEpisode();
			} else {
				$action = $this->episodeActionRepository->findByEpisodeUrl($url, $this->userService->getUserUID());
			}

			// Get episode name
			$name = (string) $item->title;

			// Get episode link
			$link = $this->stringOrNull($item->link);

			// Get episode image
			$image = $this->stringOrNull($channel->image->url);

			$itemChildren = $item->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
			if ($itemChildren) {
				$imageAttributes = (array) $itemChildren->image->attributes();
				$image = $this->stringOrNull(array_key_exists('href', $imageAttributes) ? (string) $imageAttributes['href'] : '');
				$iTunesItemChildren = $item->children('itunes', true);
				$iTunesChannelChildren = $channel->children('itunes', true);

				// Get episode duration
				if ($iTunesItemChildren) {
					$rawDuration = $this->stringOrNull($rawDuration ?? $iTunesItemChildren->duration);
				}

				if ($iTunesItemChildren && !$image) {
					$image = $this->stringOrNull($iTunesItemChildren->image['href']);
				}

				if ($iTunesChannelChildren && !$image) {
					$image = $this->stringOrNull($iTunesChannelChildren->image['href']);
				}

				if (!$image) {
					$channelChildren = $channel->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
					if ($channelChildren) {
						$imageAttributes = (array) $channelChildren->image->attributes();
						$image = $this->stringOrNull(array_key_exists('href', $imageAttributes) ? (string) $imageAttributes['href'] : '');
					}
				}

				if (!$image) {
					preg_match('/<itunes:image\s+href="([^"]+)"/', $xmlString, $matches);
					$image = $this->stringOrNull($matches[1]);
				}
			}

			// Get episode description
			$itemContent = $item->children('content', true);
			if ($itemContent) {
				$description = $this->stringOrNull($itemContent->encoded);
			} else {
				$description = $this->stringOrNull($item->description);
			}

			// Remove tags
			$description = strip_tags($description ?? '');

			// Get episode pubDate
			$rawPubDate = $this->stringOrNull($item->pubDate);
			$pubDate = $rawPubDate ? new \DateTime($rawPubDate) : null;

			// Get episode duration
			$splitDuration = array_reverse(explode(':', $rawDuration ?? ''));
			$duration = (int) $splitDuration[0];
			$duration += !empty($splitDuration[1]) ? (int) $splitDuration[1] * 60 : 0;
			$duration += !empty($splitDuration[2]) ? (int) $splitDuration[2] * 60 : 0;

			$episodes[] = new EpisodeActionExtraData(
				$podcast,
				$url,
				$name,
				$link,
				$image,
				$description,
				$fetchedAtUnix ?? (new \DateTime())->getTimestamp(),
				$guid,
				$type,
				$size,
				$pubDate,
				$duration,
				$action
			);
		}

		return $episodes;
	}

	/**
	 * @param null|\SimpleXMLElement|string $value
	 */
	private function stringOrNull($value): ?string {
		if ($value) {
			return (string) $value;
		}

		return null;
	}
}