<?php

namespace FiloBlu\Flow\Model\Actions\From;

use Exception;
use FiloBlu\Flow\Helper\Attribute;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory;

/**
 * Class Translateattribute
 * @package FiloBlu\Flow\Model\Actions\From
 */
class Translateattribute
{
    /**
     * @var string
     */
    const ENTITY_TYPE_CODE = 'product_attribute';

    /**
     * @var Attribute
     */
    protected $helperAttribute;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * Translateattribute constructor.
     * @param Attribute $helperAttribute
     * @param CollectionFactory $collectionFactory
     */
    public function __construct(
        Attribute $helperAttribute,
        CollectionFactory $collectionFactory
    ) {
        $this->helperAttribute = $helperAttribute;
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * @param $attribute
     * @param $value
     * @param $storeId
     * @throws Exception
     */
    public function process($attribute, $value, $storeId)
    {
        $values = explode(';', $value);

        if (count($values) < 2) {
            throw new Exception('Empty translation');
        }

        $attributeValue = $values[0];
        $attributeTranslation = $values[1];

        $input_type = strtolower($attribute->getFrontend()->getInputType());

        if ($attributeValue !== '' && ($input_type === 'select' || $input_type === 'multiselect')) {
            $attributeOptionId = $attribute->setStoreId(0)->getSource()->getOptionId($attributeValue);
            if (empty($attributeOptionId)) {
                $data = [
                    'attribute_id' => $attribute->getId(),
                    'store_id'     => 0,
                    'value'        => $attributeValue
                ];
                if (!($attributeOptionId = $this->helperAttribute->addAttributeOption($data))) {
                    throw new Exception('I wasn\'t able to add an attribute option');
                }
            }
            $data = [
                'option_id' => $attributeOptionId,
                'store_id'  => $storeId,
                'value'     => $attributeTranslation
            ];
            $this->helperAttribute->addAttributeTranslation($data);
        } else {
            throw new Exception('We only translate dropdown attributes');
        }
    }

}