<?php

namespace App\Twig\Components;

use App\Monitor\Framework\Repository\MonitorRepository;
use Doctrine\ORM\Query\Expr\OrderBy;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class MonitorList extends AbstractController
{
    use DefaultActionTrait;

    use PaginateTrait;

    #[LiveProp(writable: true)]
    public ?int $parentMonitorId = null;

    #[LiveProp(writable: true)]
    public string $term = "";

    #[LiveProp(writable: true)]
    public string $type = "";

    #[LiveProp(writable: true)]
    public bool $isWidget = true;

    public function __construct(
        private readonly MonitorRepository $monitorRepository,
    ) {}

    #[LiveAction]
    public function getMonitors()
    {
        if (null !== $this->parentMonitorId) {
            return $this->getChildMonitorsByParentId($this->parentMonitorId);
        } elseif ($this->type === "active") {
            return $this->getActiveUserMonitors();
        } elseif ($this->type === "complete") {
            return $this->getCompleteUserMonitors();
        }

        return [];
    }

    #[LiveAction]
    public function getActiveUserMonitors()
    {
        return $this->asPaginator($this->monitorRepository->createQueryBuilder('m')
            ->andWhere('m.status IN (:statuses)')
            ->andWhere('(m.title LIKE :term OR m.imdbId LIKE :term OR m.monitorType LIKE :term OR m.status LIKE :term)')
            ->andWhere('m.parent IS NULL')
            ->setParameter('statuses', ['New', 'In Progress', 'Active'])
            ->setParameter('term', '%'.$this->term.'%')
            ->orderBy('m.id', 'DESC')
            ->getQuery()
        );
    }

    #[LiveAction]
    public function getCompleteUserMonitors()
    {
        return $this->asPaginator($this->monitorRepository->createQueryBuilder('m')
            ->andWhere('m.status = :status')
            ->andWhere('(m.title LIKE :term OR m.imdbId LIKE :term OR m.monitorType LIKE :term OR m.status LIKE :term)')
            ->setParameter('status', 'Complete')
            ->setParameter('term', '%'.$this->term.'%')
            ->orderBy('m.id', 'DESC')
            ->getQuery()
        );
    }

    #[LiveAction]
    public function getChildMonitorsByParentId(int $parentId)
    {
        return $this->asPaginator(
            $this->monitorRepository->createQueryBuilder('m')
                ->andWhere("m.parent = :parentId")
                ->setParameter('parentId', $parentId)
                ->orderBy('m.id', 'DESC')
                ->getQuery()
        );
    }
}
