<?php

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

use Webkul\DamBundle\Entity\Asset;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;

$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();
/**
 * Converts a asset value from Akeneo PIM standard format to Akeneo PIM flat format
 *
 * Standard format:
 * [
 *      'my-asset' => [{
 *          "locale": "en_US",
 *          "scope": null,
 *          "data": [
 *                      "firstasset",
 *                      "secondassetmodule"
 *                  ]
 *      }]
 * ]
 *
 * Here is an example with the my-asset attribute.
 * Flat format:
 * [
 *      "my-asset" => "code=>firstasset&description=>asset&starred=>1&title=>First Asset&alt=>Asset&medias=>/tmp/pim/file_storage/b/9/7/e//b97e8e0c10a7daffefa87a05aaf8931cb4436a99/images.jpeg|code=>secondasset&description=>dsadasd&starred=>&title=>wew&alt=>wdasds&medias=>/tmp/pim/file_storage/9/3/a/a//93aa7b1917dcba0d8a418fdcfd4c193bc1f9b303/download.png"
 * ]
 *
 * @author    Aman Srivastava <aman.srivastava462@webkul.com>
 * @copyright Webkul Software Pvt Ltd (https://www.webkul.com)
 */
class AssetConverter extends \AbstractValueConverter
{
    protected $em;

    /** @var AttributeColumnsResolver */
    protected $columnsResolver;

    /** @var array */
    protected $supportedAttributeTypes;

    protected $fileExporterPath;

    public function __construct(
        \AttributeColumnsResolver $columnsResolver,
        array $supportedAttributeTypes,
        \Doctrine\ORM\EntityManager $em
    ) {
        parent::__construct($columnsResolver, $supportedAttributeTypes);
        $this->em = $em;
    }

    /**
     * {@inheritdoc}
     */
    
    /**
     * Converts a value
     *
     * @param string $attributeCode
     * @param mixed  $data
     *
     * @return array
     */
    public function convert($attributeCode, $data)
    {
        $convertedItem = [];

        foreach ($data as $value) {
            $flatName = $this->columnsResolver->resolveFlatAttributeName(
                $attributeCode,
                $value['locale'],
                $value['scope']
            );

            $arrayValues = !empty($value['data']) ? $value['data'] : [];
            
            $columnArray = [];
            foreach ($arrayValues as $row) {
                $rows = $this->getSingleArrayResultByCode($row);

                if (!is_array($rows) && empty($rows)) {
                    continue;
                }
                
                $rowArray = [];
                $imageArray = [];
                foreach ($rows as $key => $value) {
                    if (gettype($value) == 'string') {
                        $rowArray[] = $key . '=>' .$value;
                    } elseif (gettype($value) == 'array') {
                        if ($this->isAssoc($value)) {
                            $rowArray[] = $key . '=>' . $value['filePath'];
                        } else {
                            $imagePath = [];
                            foreach ($value as $images) {
                                $imagePath[] = isset($images['filePath'])? $images['filePath'] : null;
                            }
                            $rowArray[] = $key . '=>' . implode("!", $imagePath);
                        }
                    } elseif (gettype($value) == 'boolean') {
                        $rowArray[] = $key . '=>' .$value;
                    }
                }
                
                $columnArray[] = implode('&', $rowArray);
            }
            
            $convertedItem[$flatName] = implode('|', $columnArray);
        }
     
        return $convertedItem;
    }

    public function getSingleArrayResultByCode($identifier)
    {
        // dump($identifier);
        $result = $this->em->createQueryBuilder()
                        ->select('a, m')
                        ->from('WebkulDamBundle:Asset', 'a')
                        ->leftJoin('a.medias', 'm')
                        ->where('a.code = :identifier')
                        ->setParameter('identifier', $identifier)
                        ->getQuery()->getArrayResult();

        // dump($result);
        
        $result = count($result) !== 0 ? $result[0] : null;

        if (isset($result['medias']) && count($result['medias']) === 1) {
            $result['medias'] = reset($result['medias']);
        }
        // dump($result);
        
        return $result;
    }

    public function isAssoc(array $arr)
    {
        if (array() === $arr) {
            return false;
        }
        return array_keys($arr) !== range(0, count($arr) - 1);
    }
}
