<?php

namespace App\Security\Voter;

use App\Security\Voter\Tools\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class CommentVoter extends VoterInterface
{
    protected function supports(string $attribute, $subject): bool
    {

        return in_array($attribute, ['edit', 'delete'])
            && $subject instanceof \App\Entity\Comment;
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {

        //first, check if user is valid and has permissions
        if (!$this->checkUser($token->getUser())) {
            return false;
        }

        //then set prefix
        $this->setPermissionsPrefix('comment');

        switch ($attribute) {
            case 'edit':
                return $this->canEdit($subject);
                break;
            case 'delete':
                return $this->canDelete($subject);
                break;
        }

        return false;
    }

    private function canEdit($subject)
    {
        //user appartient au groupe du commentaire
        if ($subject->getMainGroup() === $this->user->getMainGroup()) {
            if ($subject->getCreator() === $this->user) { //c'est son propre commentaire
                return $this->hasPermission('EDIT');
            }

            return $this->hasPermission('EDIT_GROUP');
        }

        //user n'appartient pas au groupe du commentaire
        if ($subject->getMainGroup() !== $this->user->getMainGroup()) {
                return $this->hasPermission('EDIT_OTHERGROUP');
        }

        return false; //false by default
    }

    private function canDelete($subject)
    {

        //user appartient au groupe du commentaire
        if ($subject->getMainGroup() === $this->user->getMainGroup()) {
            if ($subject->getCreator() === $this->user) { //c'est son propre commentaire
                return $this->hasPermission('DELETE');
            }

            return $this->hasPermission('DELETE_GROUP');
        }

        //user n'appartient pas au groupe du commentaire
        if ($subject->getMainGroup() !== $this->user->getMainGroup()) {
                return $this->hasPermission('DELETE_OTHERGROUP');
        }

        return false; //false by default
    }
}
