<?php

namespace Lc\ShopBundle\Services ;

class ProductFamilyUtils
{
        protected $priceUtils ;

        public function __construct(PriceUtils $priceUtils)
        {
                $this->priceUtils = $priceUtils ;
        }

        public function getCheapestProduct($productFamily)
        {
                $priceUtils = $this->priceUtils ;
                return $this->getCheapestOrMostExpensiveProduct($productFamily->getProducts()->getValues(), function ($a, $b) use ($priceUtils) {
                        return $priceUtils->getPriceWithTaxAndReduction($a) > $priceUtils->getPriceWithTaxAndReduction($b) ;
                }, true);
        }

        public function getCheapestProductByRefUnit($productFamily)
        {
                $priceUtils = $this->priceUtils ;
                return $this->getCheapestOrMostExpensiveProduct($productFamily->getProducts()->getValues(), function ($a, $b) use ($priceUtils) {
                        return $priceUtils->getPriceByRefUnitWithTaxAndReduction($a) > $priceUtils->getPriceByRefUnitWithTaxAndReduction($b) ;
                }, false);
        }

        public function getMostExpensiveProductByRefUnit($productFamily)
        {
                $priceUtils = $this->priceUtils ;
                return $this->getCheapestOrMostExpensiveProduct($productFamily->getProducts()->getValues(), function ($a, $b) use ($priceUtils) {
                        return $priceUtils->getPriceByRefUnitWithTaxAndReduction($a) < $priceUtils->getPriceByRefUnitWithTaxAndReduction($b) ;
                }, false);
        }

        private function getCheapestOrMostExpensiveProduct($products, $comparisonFunction, $returnSelfIfNotActiveProducts)
        {
                if (count($products) > 0) {
                        usort($products, $comparisonFunction);
                        return $products[0];
                }
                if ($returnSelfIfNotActiveProducts) {
                        return $this;
                } 
                else {
                        return false;
                }
        }

}
