<?php

namespace Webkul\WebkulCsvImportBundle\Connector\Reader\File;

use Akeneo\Pim\Structure\Component\Repository\AttributeRepositoryInterface;

class MediaPathTransformer
{
    /** @var AttributeRepositoryInterface */
    protected $attributeRepository;

    /**
     * @param AttributeRepositoryInterface $attributeRepository
     */
    public function __construct(AttributeRepositoryInterface $attributeRepository)
    {
        $this->attributeRepository = $attributeRepository;
    }

    /**
     * Transforms a relative path to absolute. Data must be provided in the pivot format.
     *
     * $item exemple:
     * [
     *   'side_view' => [
     *     [
     *       'locale' => null,
     *       'scope'  => null,
     *       'data'   => 'cat_003.png'
     *     ]
     *   ]
     * ]
     *
     * @param array  $attributeValues An associative array (attribute_code => values)
     * @param string $filePath        The absolute path
     *
     * @return array
     */
    public function transform(array $attributeValues, $filePath)
    {
        $mediaAttributes = $this->attributeRepository->findMediaAttributeCodes();

        foreach ($attributeValues as $code => $values) {
            if (in_array($code, $mediaAttributes)) {
                foreach ($values as $index => $value) {
                    if (isset($value['data'])) {
                        $dataFilePath = $value['data'];
                        $attributeValues[$code][$index]['data'] = $dataFilePath ? $this->getPath($filePath, $dataFilePath) : null;
                    }
                }
            }
        }

        return $attributeValues;
    }

    /**
    * @param $filePath
    * @param $data
    * @return string
    */
    protected function getPath($filePath, $data)
    {
        if (filter_var($data, FILTER_VALIDATE_URL)) {
            return $this->download($data);
        }

        return sprintf('%s%s%s', $filePath, DIRECTORY_SEPARATOR, $data);
    }

    /**
    * @param string $url
    * @return string|null
    */
    protected function download(string $url)
    {
        $parsedUrl = parse_url($url);
        $dir = sprintf('%s%s%s', sys_get_temp_dir(), DIRECTORY_SEPARATOR, $parsedUrl['host']);
        $filename = sprintf('%s.%s', sha1($url), pathinfo($parsedUrl['path'], PATHINFO_EXTENSION));
        $path = sprintf('%s%s%s', $dir, DIRECTORY_SEPARATOR, $filename);
        
        try {
            $content = file_get_contents($url);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }

            file_put_contents($path, $content);

        } catch (\Exception $e) {
            return null;
        }
            return $path;
    }
}
