<?php

namespace App\Behavior;

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class UploadedBase64File extends UploadedFile
{
    public function __construct(string $base64Content, string $file_name, string $pathConfName)
    {
        $temp= explode('.',$file_name);
        $extension = end($temp);

        $fileRandomName = uniqid() . time() . '.' . $extension;

        // Delete mime type from string
        if (str_contains($base64Content, 'data:')) {
            $base64Content =  explode("base64,", $base64Content)[1];
        }

        $pathConf = Yaml::parse(file_get_contents(realpath(__DIR__.'/../..') . '/config/services/path.yaml'));
        $filePath = getcwd() . '/' . $pathConf['parameters'][$pathConfName];
        if (!file_exists($filePath)) {
            mkdir($filePath, 0777, true);
        }
        $filePath = $filePath . $fileRandomName;
        $data = base64_decode($base64Content);
        file_put_contents($filePath, $data);
        $error = null;
        $mimeType = null;
        $test = true;

        parent::__construct($filePath, $fileRandomName, $mimeType, $error, $test);
    }
}
