<?php

namespace Lc\ShopBundle\Services\Price ;

use Lc\ShopBundle\Context\OrderProductInterface;
use Lc\ShopBundle\Context\OrderShopInterface;
use Lc\ShopBundle\Context\OrderShopPriceUtilsInterface;
use Lc\ShopBundle\Context\PriceUtilsInterface;
use Lc\ShopBundle\Context\ProductPropertyInterface;

class PriceUtils implements PriceUtilsInterface
{
        protected $productPriceUtils ;
        protected $orderProductPriceUtils ;
        protected $orderShopPriceUtils ;

        public function __construct(ProductPriceUtils $productPriceUtils, OrderProductPriceUtils $orderProductPriceUtils, OrderShopPriceUtilsInterface $orderShopPriceUtils)
        {
                $this->productPriceUtils = $productPriceUtils ;
                $this->orderProductPriceUtils = $orderProductPriceUtils ;
                $this->orderShopPriceUtils = $orderShopPriceUtils ;
        }

        public function __call($name, $arguments)
        {
                $entity = $arguments[0] ;
                $service = '' ;

                if($entity instanceof ProductPropertyInterface) {
                        $service = 'productPriceUtils' ;
                }

                if($entity instanceof OrderProductInterface) {
                        $service = 'orderProductPriceUtils' ;
                }

                if($entity instanceof OrderShopInterface || is_array($entity)) {
                        $service = 'orderShopPriceUtils' ;
                }

                if(strlen($service) && $entity && method_exists($this->$service, $name)) {
                        if(isset($arguments[1]) && isset($arguments[2]) && isset($arguments[3])) {
                                return $this->$service->$name($entity, $arguments[1], $arguments[2], $arguments[3]) ;
                        }
                        elseif(isset($arguments[1]) && isset($arguments[2])) {
                                return $this->$service->$name($entity, $arguments[1], $arguments[2]) ;
                        }
                        elseif(isset($arguments[1])) {
                                return $this->$service->$name($entity, $arguments[1]) ;
                        }
                        else {
                                return $this->$service->$name($entity) ;
                        }
                }
                else {
                        if(!strlen($service)) {
                                throw new \ErrorException("PriceUtils : le type d'entité n'est pas géré.") ;
                        }
                        else {
                                if(!method_exists($this->$service, $name)) {
                                        throw new \ErrorException("PriceUtils : la méthode ".$name." du service ".$service." n'existe pas.") ;
                                }
                        }
                }

                return false ;
        }
}