<?php
namespace Leadlion\StockUpdates\Block\Adminhtml\Form\Field;

use Magento\Framework\View\Element\Html\Select;

class ManufacturerRenderer extends Select
{
    protected $eavConfig;

    public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Magento\Eav\Model\Config $eavConfig,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $data
        );
        $this->eavConfig = $eavConfig;
    }

    /**
     * Set "name" for <select> element
     *
     * @param string $value
     * @return $this
     */
    public function setInputName($value)
    {
        return $this->setName($value);
    }

    /**
     * Set "id" for <select> element
     *
     * @param $value
     * @return $this
     */
    public function setInputId($value)
    {
        return $this->setId($value);
    }

    /**
     * Render block HTML
     *
     * @return string
     */
    public function _toHtml(): string
    {
        if (!$this->getOptions()) {
            $this->setOptions($this->getSourceOptions());
        }
        return parent::_toHtml();
    }

    private function getSourceOptions(): array
    {
        $attributeOptions = $this->getManufacturers();
        $ret = [];

        foreach ($attributeOptions as $key => $item) {
            $ret[] = [
                'value' => $item['value'],
                'label' => $item['label']
            ];
        }

        return $ret;
    }

    private function getManufacturers()
    {
        $attribute = $this->eavConfig->getAttribute('catalog_product', 'manufacturer');
        $attributeOptions = $attribute->getSource()->getAllOptions();

        return $attributeOptions;
    }
}
