<?php

namespace Webkul\DamBundle\Normalizer\InternalApi;

use Akeneo\Pim\Enrichment\Component\Product\Model\ValueInterface;
use Akeneo\Pim\Enrichment\Component\Product\Normalizer\InternalApi\ImageNormalizer as BaseImageNormalizer;
use Akeneo\Pim\Enrichment\Component\Product\Normalizer\InternalApi\FileNormalizer;
/**
 * This Normalizer will normalize the "image" field, to return paths to get the image to display.
 *
 * @author    Pierre Allard <pierre.allard@akeneo.com>
 * @copyright 2017 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class ImageNormalizer extends BaseImageNormalizer
{
    /** @var FileNormalizer */
    protected $fileNormalizer;

    protected $damService;
    /**
     * @param FileNormalizer $fileNormalizer
     */
    public function __construct(FileNormalizer $fileNormalizer, $damService)
    {
        parent::__construct($fileNormalizer);
        $this->fileNormalizer = $fileNormalizer;
        $this->damService = $damService;
    }

    /**
     * Normalizes an value interface to display an image
     *
     * @param ValueInterface|null $value
     * @param string|null         $localeCode
     *
     * @return array|null
     */
    public function normalize(?ValueInterface $value, ?string $localeCode = null): ?array
    {
        if (null === $value || null === $value->getData()) {
            return null;
        }

        $attrName = $value->getAttributeCode();
        $assetAttrCodes = $this->damService->getAssetAttributeCodes();
        if(in_array($attrName, $assetAttrCodes)) {
            $asset = $value->getData();
            $asset = reset($asset);
            $data = $this->damService->getThumbnailAssetByCode($asset);
            if($data){
                $normalized = $this->fileNormalizer->normalize($data);
            } else {
                $normalized = null;
            }
             
        } else {
            $normalized = $this->fileNormalizer->normalize($value->getData());
        }

        return $normalized;
            
    }
}