<?php

namespace Webkul\DamBundle\ArrayConverter\FlatToStandard\Product\ValueConverter;

use Webkul\DamBundle\Entity\Asset;

use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;

$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
 * Converts a table value from Akeneo PIM flat format to Akeneo PIM standard format
 *
 * Here is an example with the temperature attribute.
 * Flat format:
 * [
 *      'my-table' => "column_1=>Column 1 Row 1 Value&column_2=>Column 2 Row 1 Value|column_1=>Column 1 Row 2 Value&column_2=>Column 2 Row 2 Value",
 * ]
 *
 * Standard format:
 * [
 *      'my-table' => [{
 *          "locale": "en_US",
 *          "scope": null,
 *          "data": [{
 *                   "column_1": "Column 1 Row 1 Value",
 *                   "column_2": "Column 2 Row 1 Value"
 *               }, {
 *                   "column_1": "Column 1 Row 2 Value",
 *                   "column_2": "Column 2 Row 2 Value"
 *               }
 *          ]
 *      }]
 * ]
 *
 * @author    Jitendra Singh <jitendra@webkul.com>
 * @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
 */
class AssetConverter implements \ValueConverterInterface_F2S
{
    /** @var string[] */
    protected $supportedFieldTypes;

    protected $em;
    /**
     * @param string[] $supportedFieldTypes
     */
    public function __construct(array $supportedFieldTypes, \Doctrine\ORM\EntityManager $em)
    {
        $this->supportedFieldTypes = $supportedFieldTypes;
        $this->em = $em;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsField($attributeType)
    {
        return in_array($attributeType, $this->supportedFieldTypes);
    }

    /**
     * {@inheritdoc}
     */
    public function convert(array $attributeFieldInfo, $value)
    {
        if ('' === trim($value)) {
            $data = null;
        } else {
            $data = [];
            $rowArray = explode('|', $value);
            foreach ($rowArray as $key => $row) {
                # column_1=>Column 1 Row 1 Value&column_2=>Column 2 Row 1 Value
                $columnArray = explode('&', $row);
                foreach ($columnArray as $column) {
                    # column_1=>Column 1 Row 1 Value
                    $value = explode('=>', $column);
                    
                    if ($value[0] == 'code') {
                        $data[] = $value[1];
                    }
                }
            }
        }

        return [
            $attributeFieldInfo['attribute']->getCode() => [[
                'locale' => $attributeFieldInfo['locale_code'],
                'scope'  => $attributeFieldInfo['scope_code'],
                'data'   => $data,
            ]],
        ];
    }
}
