<?php

namespace Webkul\WooCommerceBundle\Services;


/**
 * Transforms media url path to absolute path
 *
 */
class MediaPathTransformer
{
    /** @var AttributeRepositoryInterface */
    protected $attributeRepository;

    protected $overrideImages = false; 

    /**
     * @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'   => 'http://abcd.com/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)
    {          

        $imageData = []; 
        
        foreach ($attributeValues as $index => $value) {
            
            // if(array_key_exists('src',$value)) {
            if ($value) {   

                $fileContent = $this->grabImage($value['src']);
                $extension = $this->getImageMimeType($fileContent);
                $parsedUrl = parse_url($value['src']);
                
                $filePath = $filePath.$parsedUrl['path'];
                    
                $fileName = basename($filePath);    
                $fileDirectory = substr($filePath, 0,  strrpos($filePath, '/'));
                    
                $newFileDirectory = $fileDirectory .'/'. $index;

                if (!is_dir($newFileDirectory)) {
                    mkdir($newFileDirectory, 0777, true);
                }

                $newFilePath =  $newFileDirectory .'/'. $fileName;
                
                file_put_contents($newFilePath, $fileContent);
                $imageData[$index] = $newFilePath;   
                
            }
        }

        return  $imageData;
    }


    protected function grabImage($dataFilePath)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $dataFilePath);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
        $res = curl_exec($ch);
        $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch) ;
        return $res;
    }

    protected function getImageMimeType($imagedata)
    {
        $imagemimetypes = array(
            "jpeg" => "FFD8",
            "png" => "89504E470D0A1A0A",
            "gif" => "474946",
            "bmp" => "424D",
            "tiff" => "4949",
            "tiff" => "4D4D"
            );

        foreach ($imagemimetypes as $mime => $hexbytes)
        {
            $bytes = $this->getBytesFromHexString($hexbytes);
            if (substr($imagedata, 0, strlen($bytes)) == $bytes)
                return $mime;
        }

        return NULL;
    }
   
    public function getBytesFromHexString($hexdata)
    {
        for($count = 0; $count < strlen($hexdata); $count+=2)
            $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));

            return implode($bytes);
    }

}
