<?php

namespace domain\Producer\Producer;

use common\components\PageSizer;
use domain\_\AbstractManager;

class ProducerPageSizer extends AbstractManager
{
    protected ProducerSolver $producerSolver;
    protected ProducerBuilder $producerBuilder;
    protected PageSizer $pageSizer;

    public function loadDependencies(): void
    {
        $this->pageSizer = \Yii::$app->pageSizer;
        $this->producerSolver = $this->loadService(ProducerSolver::class);
        $this->producerBuilder = $this->loadService(ProducerBuilder::class);
    }

    public function getPageSizeConfigName(string $entity)
    {
        return 'option_pagesize_'.$entity;
    }

    public function getPageSize(Producer $producer, string $entity)
    {
        $pageSizeConfig = $this->getPageSizeConfigName($entity);
        return $this->producerSolver->getConfig($pageSizeConfig, $producer) ?: PageSizer::DEFAULT_PAGE_SIZE ;
    }

    public function getPageSizeSummary(Producer $producer, string $entity, string $labelEntity): string
    {
        return $this->pageSizer->getForm($entity, $labelEntity, $this->getPageSize($producer, $entity));
    }

    public function updatePagesize(Producer $producer, string $entity, int $pageSize)
    {
        $field = $this->getPageSizeConfigName($entity);

        if($producer->hasAttribute($field) && $this->pageSizer->isPageSizeExist($pageSize)) {
            $producer->$field = $pageSize;
            $this->producerBuilder->update($producer);
        }
    }
}