<?php

namespace XF\BbCode\Helper;

use XF\Entity\BbCodeMediaSite;

use function count;

class AppleMusic
{
	public const URL_REGEX = '#\.com/(?P<country>[a-z-]+)/(?P<type>album|playlist|post)/([^/]+/)?(?P<id>[a-z0-9-.]+)(\?i=(?P<song>\d+))?#i';

	public static function matchCallback($url, $matchedId, BbCodeMediaSite $site, $siteId)
	{
		if (preg_match(self::URL_REGEX, $url, $media))
		{
			if (!empty($media['song']))
			{
				$media['type'] = 'song';
				$media['id'] = $media['song'];
			}
			$matchedId = $media['country'] . '/' . $media['type'] . '/' . self::getPrefix($media['type']) . $media['id'];

			return $matchedId;
		}

		return false;
	}

	protected static function getPrefix($type)
	{
		switch (strtolower($type))
		{
			case 'post':
				return 'id';

			default:
				return '';
		}
	}

	public static function htmlCallback($mediaKey, array $site, $siteId)
	{
		$parts = explode('/', $mediaKey);
		if (count($parts) != 3)
		{
			return '';
		}

		[$country, $type, $id] = $parts;

		$country = rawurlencode($country);
		$type = rawurlencode($type);
		$id = rawurlencode($id);

		$url = "//embed.music.apple.com/{$country}/{$type}/{$id}?app=music";
		$style = '';
		$scrolling = 'auto';

		switch ($type)
		{
			case 'post':
				$height = 315;
				$url = "//embed.itunes.apple.com/embedded-player/{$country}/{$type}/{$id}";
				$scrolling = 'no';
				break;

			case 'song':
				$height = 150;
				break;

			case 'album':
			case 'playlist':
			default:
				$height = 500;
		}

		return \XF::app()->templater()->renderTemplate('public:_media_site_embed_applemusic', [
			'country' => $country,
			'type' => $type,
			'siteId' => $siteId,
			'id' => $id,
			'url' => $url,
			'height' => $height,
			'style' => $style,
			'scrolling' => $scrolling,
		]);
	}
}
