<?php

// Documentation :

// gestion de la colonne ordre
// https://labs.madisoft.it/avoiding-uniqueconstraintviolationexception-due-to-doctrine-commit-order/


namespace App\Entity;

use App\Entity\Trait\UniqueOrderTrait;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Trait\DeletableTrait;
use App\Entity\Trait\TimestampableTrait;
use App\Entity\Interface\IUniqueOrderable;
use Doctrine\ORM\Mapping\UniqueConstraint;
use App\Entity\Listener\UniqueOrdreListener;
use App\Repository\EventPerformerRepository;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

#[ORM\HasLifecycleCallbacks]
#[UniqueEntity(fields: ["event", "ordre", "enabledOrdreUniqueKey"], message: "admin.event-performer.fields.@event+ordre.errors.already-existing")]
#[UniqueConstraint(name: "IDX_event_performer_event_id_ordre", columns: ["event_id", "ordre", "enabledOrdreUniqueKey"])]
#[ORM\EntityListeners([UniqueOrdreListener::class])]
#[ORM\Entity(repositoryClass: EventPerformerRepository::class)]
#[ORM\Table(name: 'event_performer')]
class EventPerformer implements IUniqueOrderable
{
    use DeletableTrait;
    use TimestampableTrait;
    use UniqueOrderTrait;

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'performers')]
    #[ORM\JoinColumn(name:'event_id', nullable: false)]
    private ?Event $event = null;

    #[ORM\Column(length: 255)]
    private ?string $name = null;

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

    public function getEvent(): ?Event
    {
        return $this->event;
    }

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

    public function setEvent(?Event $event): static
    {
        $this->event = $event;

        return $this;
    }

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

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

        return $this;
    }

    # gestion de l'ORDRE

    function getTableName() : string {
        return "event_performer";
    }

    function getPartitionByColumns() : array {
        return [[
                    "name" => "event_id",
                    "type" => "int"
                ]];
    }

    public function __serialize() : array
    {
        return [
            "id"       =>          $this->id,
            "event"    => ["id" => ($this->event   ? $this->event->getId()   : -1)],
            "name"     =>          $this->name,
            "ordre"    =>          $this->getOrdre()
        ];
    }

    public function __unserialize(array $data)
    {
        $this->id    = $data["id"];
        $this->event = null; // ignore
        $this->name  = $data["name"];
        $this->setOrdre($data["ordre"]);
    }
}
