<?php

namespace AutoAdmin\Bundle\Admin\Model;

use AutoAdmin\Bundle\Content\Entity\Log;
use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Entity\Traits\CreatedAtTrait;
use AutoAdmin\Bundle\Content\Entity\Traits\UpdatedAtTrait;
use AutoAdmin\Bundle\Content\Model\CreatedAtInterface;
use AutoAdmin\Bundle\Content\Model\UpdatedAtInterface;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
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;

#[UniqueEntity(fields: 'email', message: 'Email déjà pris')]
#[UniqueEntity(fields: 'username', message: 'Username déjà pris')]
#[ORM\Table(name: 'admin')]
#[ORM\MappedSuperclass]
#[ORM\HasLifecycleCallbacks]
abstract class AdministratorModel implements UserInterface, PasswordAuthenticatedUserInterface, CreatedAtInterface, UpdatedAtInterface
{
    use CreatedAtTrait;
    use UpdatedAtTrait;

    #[ORM\Column(type: Types::STRING, length: 255, unique: true)]
    protected string $email;

    #[ORM\Column(type: Types::STRING, length: 255, unique: true)]
    protected string $username;

    #[ORM\Column(type: Types::STRING, length: 255)]
    protected string $password;

    protected ?string $plainPassword = null;

    protected string $salt;

    #[ORM\Column(type: Types::JSON)]
    protected array $roles = ['ROLE_ADMIN'];

    #[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)]
    protected ?DateTime $lastLoggedAt = null;

    #[ORM\Column(type: Types::STRING, length: 255, nullable: true)]
    protected ?string $passwordRequestToken = null;

    #[ORM\Column(type: Types::DATETIME_MUTABLE, nullable: true)]
    protected ?DateTime $passwordRequestAt = null;

    #[ORM\Column(type: Types::BOOLEAN, options: ['default' => true])]
    protected bool $enabled = true;

    #[ORM\ManyToMany(targetEntity: Site::class)]
    protected Collection $sites;

    #[ORM\OneToMany(mappedBy: 'administrator', targetEntity: Log::class)]
    protected Collection $logs;

    public function __construct()
    {
        $this->createdAt = new DateTime();
        $this->sites = new ArrayCollection();
        $this->logs = new ArrayCollection();
    }

    public function __toString(): string
    {
        return (string)(!empty($this->username)) ? $this->username : '';
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

    public function addRole(string $role): void
    {
        if (!in_array($role, $this->roles)) {
            $this->roles[] = $role;
        }
    }

    public function removeRole(string $role): void
    {
        foreach ($this->roles as $key => $value) {
            if ($value === $role) {
                unset($this->roles[$key]);
            }
        }
    }

    public function getRoles(): array
    {
        $roles = $this->roles;
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

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

        return $this;
    }

    public function hasRole(string $role): bool
    {
        return in_array($role, $this->roles);
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

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

        return $this;
    }

    public function getPlainPassword(): ?string
    {
        return $this->plainPassword;
    }

    public function setPlainPassword(?string $plainPassword): self
    {
        $this->plainPassword = $plainPassword;

        return $this;
    }

    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    public function eraseCredentials(): void
    {
        $this->plainPassword = null;
    }

    #[ORM\PreUpdate]
    public function onUpdate(): void
    {
        $this->updatedAt = new DateTime();
    }

    public function getLastLoggedAt(): ?DateTime
    {
        return $this->lastLoggedAt;
    }

    public function setLastLoggedAt(?DateTime $dateTime): self
    {
        $this->lastLoggedAt = $dateTime;

        return $this;
    }

    public function getEnabled(): bool
    {
        return $this->enabled;
    }

    public function setEnabled(bool $enabled): self
    {
        $this->enabled = $enabled;

        return $this;
    }

    public function getPasswordRequestToken(): ?string
    {
        return $this->passwordRequestToken;
    }

    public function setPasswordRequestToken(?string $token): self
    {
        $this->passwordRequestToken = $token;

        return $this;
    }

    public function getPasswordRequestAt(): ?DateTime
    {
        return $this->passwordRequestAt;
    }

    public function setPasswordRequestAt(?DateTime $time): self
    {
        $this->passwordRequestAt = $time;

        return $this;
    }

    public function getSites(): Collection
    {
        return $this->sites;
    }

    public function addSite(Site $site): self
    {
        if (!$this->sites->contains($site)) {
            $this->sites->add($site);
        }

        return $this;
    }

    public function removeSite(Site $site): self
    {
        if ($this->sites->contains($site)) {
            $this->sites->removeElement($site);
        }

        return $this;
    }

    /**
     * @return Collection<Log>
     */
    public function getLogs(): Collection
    {
        return $this->logs;
    }

    public function addLog(Log $log): self
    {
        if (!$this->logs->contains($log)) {
            $this->logs[] = $log;
            $log->setAdministrator($this);
        }

        return $this;
    }

    public function removeLog(Log $log): self
    {
        // set the owning side to null (unless already changed)
        if ($this->logs->removeElement($log) && $log->getAdministrator() === $this) {
            $log->setAdministrator(null);
        }

        return $this;
    }
}
