<?php

namespace App\User\Framework\Entity;

use Aimeos\Map;
use App\Download\Framework\Entity\Download;
use App\EventLog\Framework\Entity\EventLog;
use App\Monitor\Framework\Entity\Monitor;
use App\User\Framework\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\HasLifecycleCallbacks]
#[UniqueEntity(fields: ['email'], message: 'There is already an account with this email')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'string', length: 255, nullable: true)]
    private ?string $username;

    #[ORM\Column(type: 'string', length: 180, unique: true)]
    private ?string $email;

    #[ORM\Column(type: 'string', length: 255, nullable: true)]
    private ?string $name;

    #[ORM\Column(type: 'json')]
    private array $roles = [];

    #[ORM\Column(type: 'string')]
    private string $password;

    /**
     * @var Collection<int, UserPreference>
     */
    #[ORM\OneToMany(targetEntity: UserPreference::class, mappedBy: 'user', cascade: ['persist', 'remove'])]
    private Collection $userPreferences;

    /**
     * @var Collection<int, Monitor>
     */
    #[ORM\OneToMany(targetEntity: Monitor::class, mappedBy: 'user', orphanRemoval: true)]
    private Collection $monitors;

    /**
     * @var Collection<int, Download>
     */
    #[ORM\OneToMany(targetEntity: Download::class, mappedBy: 'user')]
    private Collection $downloads;

    /**
     * @var Collection<int, EventLog>
     */
    #[ORM\OneToMany(targetEntity: EventLog::class, mappedBy: 'user')]
    private Collection $eventLogs;

    public function __construct()
    {
        $this->userPreferences = new ArrayCollection();
        $this->monitors = new ArrayCollection();
        $this->downloads = new ArrayCollection();
        $this->eventLogs = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(?string $name): self
    {
        $this->name = $name;

        return $this;
    }

    /**
     * The public representation of the user (e.g. a username, an email address, etc.)
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials(): void
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    /**
     * @return Collection<int, UserPreference>
     */
    public function getUserPreferences(): Collection
    {
        return $this->userPreferences;
    }

    public function getUserPreference(string $preferenceName): ?UserPreference
    {
        foreach ($this->userPreferences as $userPreference) {
            if ($userPreference->getPreference()->getName() === $preferenceName
                || $userPreference->getPreference()->getId() === $preferenceName
            ) {
                return $userPreference;
            }
        }
        return null;
    }

    public function hasUserPreference(string $preferenceName): bool
    {
        foreach ($this->userPreferences as $userPreference) {
            if ($userPreference->getPreference()->getId() === $preferenceName) {
                return true;
            }
        }
        return false;
    }

    public function updateUserPreference(string $preferenceName, mixed $preferenceValue): static
    {
        foreach ($this->userPreferences as $userPreference) {
            if ($userPreference->getPreference()->getId() === $preferenceName) {
                $userPreference->setPreferenceValue($preferenceValue);
            }
        }
        return $this;
    }

    public function addUserPreference(UserPreference $userPreference): static
    {
        if (!$this->userPreferences->contains($userPreference)) {
            $this->userPreferences->add($userPreference);
            $userPreference->setUser($this);
        }

        return $this;
    }

    public function removeUserPreference(UserPreference $userPreference): static
    {
        if ($this->userPreferences->removeElement($userPreference)) {
            // set the owning side to null (unless already changed)
            if ($userPreference->getUser() === $this) {
                $userPreference->setUser(null);
            }
        }

        return $this;
    }

    public function getUserPreferenceValues(string $type = 'all'): array
    {
        return Map::from($this->userPreferences)
            ->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
            ->map(function (UserPreference $userPreference) {
                if (in_array($userPreference->getPreference()->getId(), ['language', 'provider', 'quality'])) {
                    return $userPreference->getPreferenceValue();
                }
                return null;
            })
            ->toArray();
    }

    /**
     * @return Collection<int, Monitor>
     */
    public function getMonitors(): Collection
    {
        return $this->monitors;
    }

    public function addMonitor(Monitor $monitor): static
    {
        if (!$this->monitors->contains($monitor)) {
            $this->monitors->add($monitor);
            $monitor->setUser($this);
        }

        return $this;
    }

    public function removeMonitor(Monitor $monitor): static
    {
        if ($this->monitors->removeElement($monitor)) {
            // set the owning side to null (unless already changed)
            if ($monitor->getUser() === $this) {
                $monitor->setUser(null);
            }
        }

        return $this;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(?string $username): static
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @return Collection<int, Download>
     */
    public function getDownloads(): Collection
    {
        return $this->downloads;
    }

    public function getMediaPreferences()
    {
        return Map::from($this->userPreferences)
            ->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
            ->filter(fn(UserPreference $userPreference) => $userPreference->getPreference()->getType() === 'media')
            ->toArray()
            ;
    }

    public function getDownloadPreferences()
    {
        return Map::from($this->userPreferences)
            ->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
            ->filter(fn(UserPreference $userPreference) => $userPreference->getPreference()->getType() === 'download')
            ->toArray()
            ;
    }

    /**
     * @return Collection<int, Download>
     */
    public function getActiveDownloads(): Collection
    {
        return $this->downloads->filter(fn(Download $download) => in_array($download->getStatus(), ['New', 'In Progress']));
    }

    public function addDownload(Download $download): static
    {
        if (!$this->downloads->contains($download)) {
            $this->downloads->add($download);
            $download->setUser($this);
        }

        return $this;
    }

    public function removeDownload(Download $download): static
    {
        if ($this->downloads->removeElement($download)) {
            // set the owning side to null (unless already changed)
            if ($download->getUser() === $this) {
                $download->setUser(null);
            }
        }

        return $this;
    }

    public function queryDownloads(string $type = 'complete', int $limit = 5)
    {
        if ($type === 'complete') {
            return $this->downloads->filter(fn($item) => in_array($item->getStatus(), ['Complete']))->slice(0, $limit);
        } elseif ($type === 'in-progress') {
            return $this->downloads->filter(fn($item) => in_array($item->getStatus(), ['New', 'In Progress']))->slice(0, $limit);
        }
        return [];
    }

    public function getCalendarPreferences(): array
    {
        return Map::from($this->userPreferences)
            ->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
            ->filter(fn(UserPreference $userPreference) => $userPreference->getPreference()->getType() === 'calendar')
            ->toArray()
            ;
    }

    public function hasICalEnabled(): bool
    {
        return $this->hasUserPreference('enable_ical_up_ep') &&
            (bool) $this->getUserPreference('enable_ical_up_ep')->getPreferenceValue() === true;
    }

    /**
     * @return Collection<int, EventLog>
     */
    public function getEventLogs(): Collection
    {
        return $this->eventLogs;
    }

    public function addEventLog(EventLog $eventLog): static
    {
        if (!$this->eventLogs->contains($eventLog)) {
            $this->eventLogs->add($eventLog);
            $eventLog->setUser($this);
        }

        return $this;
    }

    public function removeEventLog(EventLog $eventLog): static
    {
        if ($this->eventLogs->removeElement($eventLog)) {
            // set the owning side to null (unless already changed)
            if ($eventLog->getUser() === $this) {
                $eventLog->setUser(null);
            }
        }

        return $this;
    }
}
