<?php declare(strict_types=1);

/*
 * This file is part of the Rapsys TreeBundle package.
 *
 * (c) Raphaël Gertz <symfony@rapsys.eu>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Rapsys\TreeBundle\Repository;

use Doctrine\ORM\Query\ResultSetMapping;

use Rapsys\TreeBundle\Repository;

/**
 * Album repository
 */
class AlbumRepository extends Repository {
	/**
	 * Find album count as int
	 *
	 * @param ?integer $id The user id
	 * @return integer The albums count
	 */
	public function findCountAsInt(?int $id): int {
		//Set user sql
		$userSql = <<<SQL
a.user_id = :id
SQL;

		//With null id
		if ($id === null) {
			//Set user sql
			$userSql = <<<SQL
a.user_id IS NULL
SQL;
		}

		//Set the request
		$req = <<<SQL
SELECT COUNT(DISTINCT a.album_id) AS count
FROM Rapsys\TreeBundle\Entity\Element AS a
WHERE $userSql
SQL;

		//Get result set mapping instance
		$req = $this->replace($req);

		//Get result set mapping instance
		//XXX: DEBUG: see ../blog.orig/src/Rapsys/BlogBundle/Repository/ArticleRepository.php
		$rsm = new ResultSetMapping();

		//Declare all fields
		//XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
		//addScalarResult($sqlColName, $resColName, $type = 'string');
		$rsm->addScalarResult('count', 'count', 'integer');

		//Get result
		return $this->_em
			->createNativeQuery($req, $rsm)
			->setParameter('id', $id)
			->getSingleScalarResult();
	}

	/**
	 * Find albums as array
	 *
	 * @param ?integer $id The user id
	 * @param integer $page The page
	 * @param integer $count The count
	 * @return array The albums array
	 */
	public function findAllAsArray(?int $id, int $page, int $count): array {
		//Set user sql
		$userSql = <<<SQL
e.user_id = :id
SQL;

		//With null id
		if ($id === null) {
			//Set user sql
			$userSql = <<<SQL
e.user_id IS NULL
SQL;
		}

		//Set the request
		$req = <<<SQL
SELECT
	a.id,
	a.path,
	GROUP_CONCAT(e.id ORDER BY e.id SEPARATOR "\\n") AS s_ids,
	GROUP_CONCAT(IFNULL(e.path, '/') ORDER BY e.id SEPARATOR "\\n") AS s_paths,
	a.slug,
	GREATEST(a.created, e.created) AS created,
	GREATEST(a.updated, e.updated) AS updated,
	GREATEST(a.created, e.created, a.updated, e.updated) AS modified
FROM Rapsys\TreeBundle\Entity\Album AS a
JOIN Rapsys\TreeBundle\Entity\Element AS e ON (e.album_id = a.id AND {$userSql})
GROUP BY a.id
ORDER BY updated, created DESC, a.id
LIMIT :offset, :count
SQL;

		//Replace bundle entity name by table name
		$req = $this->replace($req);

		//Get result set mapping instance
		$rsm = new ResultSetMapping();

		//Declare all fields
		//XXX: see vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Types.php
		//addScalarResult($sqlColName, $resColName, $type = 'string');
		$rsm->addScalarResult('id', 'id', 'integer')
			->addScalarResult('path', 'path', 'string')
			->addScalarResult('slug', 'slug', 'string')
			->addScalarResult('s_ids', 's_ids', 'string')
			->addScalarResult('s_paths', 's_paths', 'string')
			->addScalarResult('created', 'created', 'datetime')
			->addScalarResult('updated', 'updated', 'datetime')
			->addScalarResult('modified', 'modified', 'datetime')
			->addIndexByScalar('id');

		//Get result
		$result = $this->_em
			->createNativeQuery($req, $rsm)
			->setParameter('offset', $page * $count)
			->setParameter('count', $count)
			->setParameter('id', $id)
			->getArrayResult();

		//Set return
		$return = [];

		//Iterate on each city
		foreach($result as $data) {
			//Add to return
			$return[$data['id']] = [
				'id' => $id = $data['id'],
				'slug' => $slug = $data['slug'],
				'path' => $data['path'],
				'created' => $data['created'],
				'updated' => $data['updated'],
				'modified' => $data['modified'],
				'link' => $this->router->generate('rapsystree_album', ['id' => $id, 'slug' => $slug, 'path' => '/']),
				'elements' => []
			];

			//Explode element ids
			$data['s_ids'] = explode("\n", $data['s_ids']);

			//Explode element paths
			$data['s_paths'] = explode("\n", $data['s_paths']);

			foreach($data['s_ids'] as $s => $id) {
				$return[$data['id']]['elements'][$id] = [
					'id' => $id,
					'path' => $path = $data['s_paths'][$s],
					'link' => $this->router->generate('rapsystree_element', ['id' => $id, 'path' => $path]),
				];
			}
		}

		//Return return
		return $return;
	}
}