<?php

namespace Lc\ShopBundle\Services ;

use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\PointSaleInterface;
use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Context\UserPointSaleInterface;

class PointSaleUtils
{
        protected $em ;

        public function __construct(EntityManagerInterface $em)
        {
                $this->em = $em ;
        }

        public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
        {
                foreach($user->getUserPointSales() as $userPointSale) {
                        if($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
                                return true ;
                        }
                }
                return false ;
        }

        public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
        {
                if(!$this->isUserLinkedToPointSale($user, $pointSale)) {
                        $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
                        $userPointSale = new $userPointSaleClass ;

                        $userPointSale->setUser($user) ;
                        $userPointSale->setPointSale($pointSale) ;

                        $this->em->persist($userPointSale);
                        $this->em->flush() ;
                }
        }

}
