<?php

namespace Lc\ShopBundle\Controller\Admin;

use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
use Symfony\Component\Security\Core\Security;

class AdminController extends EasyAdminController
{

        protected $security;

        public function __construct(Security $security)
        {
                $this->security = $security;
        }

        public function updateEntity($entity)
        {
                $this->setUpdated($entity);
                parent::updateEntity($entity);
        }

        public function persistEntity($entity)
        {

                if (method_exists($entity, 'setMerchant')) {
                        $entity->setMerchant($this->security->getUser()->getMerchant());

                }

                if (method_exists($entity, 'setCreatedAt')) {
                        $entity->setCreatedAt(new \DateTime());
                }

                if (method_exists($entity, 'setCreatedAt')) {
                        $entity->setCreatedBy($this->security->getUser());
                }

                if (method_exists($entity, 'getAddress')
                        && method_exists($entity->getAddress(), 'setCreatedBy')) {
                        $entity->getAddress()->setCreatedBy($this->security->getUser());
                }

                $this->setUpdated($entity);

                if (method_exists($entity, 'setPosition')) {
                        $entity->setPosition(0);
                }

                if (method_exists($entity, 'setStatus')) {
                        $entity->setStatus(1);
                }

                parent::persistEntity($entity);
        }

        public function setUpdated($entity)
        {
                if (method_exists($entity, 'setUpdatedAt')) {
                        $entity->setUpdatedAt(new \DateTime());
                }

                if (method_exists($entity, 'setUpdatedAt')) {
                        $entity->setUpdatedBy($this->security->getUser());
                }

                if (method_exists($entity, 'getAddress')
                        && method_exists($entity->getAddress(), 'setUpdatedBy')) {

                        $entity->getAddress()->setUpdatedBy($this->security->getUser());
                }
        }

}