<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\Judge;
use Doctrine\ORM\EntityManager;
use UtilityModule\Hydrator\DoctrineObject;

class JudgeManager
{
    const SORT_LOCALE = 'hu_HU.UTF8';
    const IMAGE_DIRECTORY = 'data/user-data/images/judge';

    /** @var EntityManager */
    private $entityManager;

    /** @var DoctrineObject */
    private $hydrator;

    public function __construct(
        EntityManager $entityManager,
        DoctrineObject $hydrator
    ) {
        $this->entityManager = $entityManager;
        $this->hydrator = $hydrator;
    }

    /**
     * @return Judge[]|null
     */
    public function getJudges(): ?array
    {
        $qb = $this->entityManager->createQueryBuilder();
        $result = $qb->select('j, t')
            ->from(Judge::class, 'j')
            ->leftJoin('j.titles', 't')
            ->orderBy('j.name', 'ASC')
            ->addOrderBy('t.year', 'ASC')
            ->getQuery()
            ->getResult();
        return $this->sortJudgesResult($result);
    }

    /**
     * @param int $year
     * @return Judge[]|null
     */
    public function getJudgesByYear(int $year): ?array
    {
        $qb = $this->entityManager->createQueryBuilder();
        $result =  $qb->select('j,t')
            ->from(Judge::class, 'j')
            ->innerJoin('j.titles', 't')
            ->where('t.year = :year')
            ->orderBy('j.name', 'ASC')
            ->setParameter('year', $year)
            ->getQuery()
            ->getResult();
        return $this->sortJudgesResult($result);
    }

    private function sortJudgesResult(array $judges): array
    {
        setlocale(LC_COLLATE, self::SORT_LOCALE);
        usort($judges, function (Judge $a, Judge $b) {
            return strcoll($a->getName(), $b->getName());
        });
        return $judges;
    }

    /**
     * @param int $id
     * @return Judge|null
     */
    public function getJudge(int $id): ?Judge
    {
        /** @var Judge $judge */
        $judge = $this->entityManager->getRepository(Judge::class)->find($id);
        return $judge;
    }

    /**
     * @param $data
     * @return Judge
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function create($data): Judge
    {
        unset($data['slug']);
        /** @var Judge $judge */
        $judge = $this->hydrator->hydrate($data, new Judge());
        $this->entityManager->persist($judge);
        $this->entityManager->flush();
        return $judge;
    }

    /**
     * @param int $id
     * @param $data
     * @return Judge
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function update(int $id, $data): Judge
    {
        unset($data['slug']);
        $judge = $this->entityManager->getRepository(Judge::class)->find($id);
        /** @var Judge $judge */
        $judge = $this->hydrator->hydrate($data, $judge);
        $this->entityManager->persist($judge);
        $this->entityManager->flush();
        return $judge;
    }

    /**
     * @param int $id
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(int $id): bool
    {
        if (null !== ($entity = $this->getJudge($id))) {
            $this->entityManager->remove($entity);
            $this->entityManager->flush();
            return true;
        }
        return false;
    }

    /**
     * @param string $slug
     * @return string
     */
    public function getProfileImage(string $slug): string
    {
        /** @var Judge $entity */
        $entity = $this->entityManager->getRepository(Judge::class)->findOneBy([
          'slug' => $slug,
        ]);
        $fileName = $this->getImageFileName($entity->getId());
        if (file_exists($fileName)) {
            return file_get_contents($fileName);
        }
        throw new \InvalidArgumentException();
    }

    /**
     * @param string $slug
     * @param string $imageData
     * @return bool
     */
    public function setProfileImage(string $slug, string $imageData): bool
    {
        /** @var Judge $entity */
        $entity = $this->entityManager->getRepository(Judge::class)->findOneBy([
          'slug' => $slug,
        ]);
        $this->ensureImageDirectoryExists();
        $fileName = $this->getImageFileName($entity->getId());
        return false !== file_put_contents($fileName, $imageData);
    }

    /**
     * @param string $slug
     * @return bool
     */
    public function deleteProfileImage(string $slug): bool
    {
        /** @var Judge $entity */
        $entity = $this->entityManager->getRepository(Judge::class)->findOneBy([
          'slug' => $slug,
        ]);
        $fileName = $this->getImageFileName($entity->getId());
        if (file_exists($fileName)) {
            return unlink($fileName);
        }
        throw new \InvalidArgumentException();
    }

    public function ensureImageDirectoryExists()
    {
        if (!is_dir(self::IMAGE_DIRECTORY)) {
            mkdir(self::IMAGE_DIRECTORY, 0755, true);
        }
    }

    private function getImageFileName(int $id): string
    {
        return sprintf('%s/%s.jpg', self::IMAGE_DIRECTORY, $id);
    }
}
