<?

namespace Shop\Modules\AdminComplexRates;

use Core\Form\RepoForm;
use Core\Registry\Column;
use Core\Registry\Field;
use Core\Registry\RepoRegisry;
use Shop\Repositories\Category;

/**
 * Description of AdminComplexRates
 * @todo добавить город страну регион
 * @author Diamond Code Generator
 */
class AdminComplexRates extends \Core\ModuleController
{

    protected $repo;
    protected $tableFactory;
    protected $cBuilder;
    protected $brandRepo;
    protected $groupRepo;
    protected $customerRepo;
    protected $shopRepo;
    protected $pricelistSheetRepo;
    protected $categoryRepo;

    function __construct(\Diamond\Factory\Table $tableFactory, \Core\Form\ControlBuilder $cBuilder,
                         \Shop\Repositories\ComplexRate $repo, \Shop\Repositories\Brand $brandRepo,
                         \Shop\Repositories\CustomerGroup $groupRepo, \Shop\Repositories\Customer $customerRepo,
                         \Shop\Repositories\Shop $shopRepo, \Shop\Repositories\PricelistSheet $pricelistSheetRepo,
                            Category $categoryRepo
    )
    {
        $this->tableFactory = $tableFactory;
        $this->repo = $repo;
        $this->cBuilder = $cBuilder;
        $this->brandRepo = $brandRepo;
        $this->customerRepo = $customerRepo;
        $this->groupRepo = $groupRepo;
        $this->shopRepo = $shopRepo;
        $this->pricelistSheetRepo = $pricelistSheetRepo;
        $this->categoryRepo = $categoryRepo;
    }

    public function process()
    {

        /**
         * @var RepoRegisry $table
         */
        $table = $this->tableFactory->buildAdminTable("complex_rates", $this->repo);

        $table->getForm()->addValidationSuccessEvent([$this,"clearCache"]);

        $table
                ->addColumn(new Column("id", "№", 20, false, true))
                ->addColumn((new Column("brandId", "Производитель", 120))->setFn($this, "formatBrand"))
                ->addColumn((new Column("customerGroupId", "Группа клиента", 120))->setFn($this, "formatGroup"))
                ->addColumn((new Column("customerId", "Клиент", 120))->setFn($this, "formatCustomer"))
                ->addColumn((new Column("shopId", "Офис", 90))->setFn($this, "formatShop"))
                ->addColumn((new Column("pricelistSheetId", "Прайс-лист", 90))->setFn($this, "formatPriceList"))
                ->addColumn((new Column("categoryId", "Категория товара", 90))->setFn($this, "formatCategory"))
                ->addColumn((new Column("rate", "Скидка/Наценка,%", 60))->setFn($this, "formatRate"))
                ->addColumn(new Column("priority", "Приоритет", 60))
                ->addColumn((new Column("active", "Активна", 60))->setFn($this, "formatActive"))
        ;

        $brands = \Shop\Helpers\Form::prepareDropdownWithDef($this->brandRepo,"%","производитель");
        $groups = \Shop\Helpers\Form::prepareDropdownWithDef($this->groupRepo,"%","группа клиента");
        $customers = \Shop\Helpers\Form::prepareDropdownWithDef($this->customerRepo,"%","клиент");
        $shops = \Shop\Helpers\Form::prepareDropdownWithDef($this->shopRepo,"%","офис");
        $prices = \Shop\Helpers\Form::prepareDropdownWithDef($this->pricelistSheetRepo,"%","прайс-лист");
        $categories = \Shop\Helpers\Form::prepareDropdownWithDef($this->categoryRepo,"%","категорию товара","getDropdownListAllWithParent");

        $pri = [];
        for($pr=0; $pr<=100; $pr++){
            $pri []= $pr;
        }
        
        $table
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInputLittle("rate"), null, "required", "пример: 15.5% -наценка, -20.5% -скидка"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("brandId", $brands)
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("customerGroupId", $groups)
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("customerId", $customers)
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("shopId", $shops)
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("pricelistSheetId", $prices)
                ))
                ->addField(
                new Field(
                    $this->cBuilder
                        ->buildDropdownUniform("categoryId", $categories)
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("priority", $pri)
                ))
                ->addField(
                    new Field(
                        $this->cBuilder
                            ->buildDropdownYNDigitUniform("active")
                    ))
        ;

        return $table->render();
    }


    public function clearCache(array $data, RepoForm $form){
        $driver = \TFC\Cache\DoctrineCacheFactory::factory('memcache');
        $driver ->flushAll();

        $driver = \TFC\Cache\DoctrineCacheFactory::factory('memcache');
        $driver->setNamespace("modules");
        $driver ->flushAll();

        $form->addCustomMessage("Кеш товаров успешно сброшен");
    }

    /**
     * 
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     * @return type
     */
    public function formatPriceList(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getPricelistSheetId() > 0 && $list = $this->pricelistSheetRepo->findById($rate->getPricelistSheetId())) {
            return $list->getTitle();
        }

        return $rate->getPricelistSheetId();        
    }
    
    /**
     * 
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatBrand(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getBrandId() > 0 && $brand = $this->brandRepo->findById($rate->getBrandId())) {
            return $brand->getName();
        }

        return $rate->getBrandId();
    }

    /**
     * 
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatGroup(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getCustomerGroupId() > 0 && $group = $this->groupRepo->findById($rate->getCustomerGroupId())) {
            return $group->getName();
        }


        return $rate->getCustomerGroupId();
    }

    /**
     * 
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatCustomer(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getCustomerId() > 0 && $customer = $this->customerRepo->findById($rate->getCustomerId())) {
            return $customer->getName();
        }

        return $rate->getCustomerId();
    }

    /**
     * 
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatShop(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        if ($rate->getShopId() > 0 && $shop = $this->shopRepo->findById($rate->getShopId())) {
            return $shop->getTitle();
        }

        return $rate->getShopId();
    }

    public function formatCategory(\Shop\Models\ComplexRate\ComplexRate $rate){
        /**
         * @var \Shop\Models\Category\Category $category
         */
        if ($rate->getCategoryId() > 0 && $category = $this->categoryRepo->findById($rate->getCategoryId())) {
            return $category->getnameWithParent();
        }

        return $rate->getCategoryId();
    }

    /**
     * 
     * @param \Shop\Models\ComplexRate\ComplexRate $rate
     */
    public function formatRate(\Shop\Models\ComplexRate\ComplexRate $rate)
    {
        return $rate->getRate();
    }

    public function formatActive(\Shop\Models\ComplexRate\ComplexRate $rate){
        return $rate->getActive()=== 1 ? "Да": "Нет";
    }

}