<?php
/**
 * @package     MefisAssetBridge
 * @subpackage  MefisAssetBridgeCore_DTO
 *
 * @copyright   Copyright (C) 2025 Goran Usljebrka. All rights reserved.
 * @license     Proprietary — No resale or incorporation into other projects without explicit written permission. see LICENSE.txt
 */

namespace MefisAssetBridgeCore\DTO;
use MefisAssetBridgeCore\Traits\Encryptor;
use JsonSerializable;
/**
 * Thumbnail DTO
 */
class ThumbnailDto implements JsonSerializable
{
    use Encryptor;
    public string $data;
    public string $extension;
    public int    $width;
    public int    $height;
    public int    $size;
    public string $resolution;
    public string $type;
    // public string $device;
    public string $timestamp;
    private string $tmpFile;
    public function __construct ($data = [], $masterKey = '')
    {
        $this->data = $data['data'] ?? '';
        // Automatically parse extension from data string
        if (!empty($this->data)) {
            $parts = explode(':', $this->data, 2);
            if (count($parts) === 2) {
                $mime = explode(';', $parts[1], 2)[0];
                $this->extension = explode('/', $mime, 2)[1] ?? '';
            }
        }
        $this->width = $data['width'] ?? 0;
        $this->height = $data['height'] ?? 0;
        // $this->size = $data['size'] ?? 0;
        $this->resolution = $data['resolution'] ?? '';
        $this->type = $data['type'] ?? '';
        // $this->device = $data['device'] ?? '';
        $this->timestamp = $data['timestamp'] ?? '';
        $this->setEncryptorKey($masterKey);
        $this->_createTemporaryFile();

    }
    private function _createTemporaryFile() {
        if(empty($this->data)) {
            return;
        }
        $parts = explode(',', $this->data, 2);
        if(count($parts) !== 2) {
            return;
        }
        $base64 = $parts[1];
        $decoded = base64_decode($base64, true);
        if($decoded === false) {
            return;
        }

        // Encrypt the decoded binary data
        $encrypted = $this->encrypt($decoded);

        // Decode the base64-encrypted string back to binary for temp file
        $encryptedBinary = base64_decode($encrypted, true);
        if($encryptedBinary === false) {
            return;
        }
        $tmpFile = tempnam(sys_get_temp_dir(), 'mefis_thumbnail_') . '.' . $this->extension;
        file_put_contents($tmpFile, $encryptedBinary);
        $this->tmpFile = $tmpFile;
    }

    public function getTemporaryFilePath(): ?string
    {
        return $this->tmpFile ?? null;
    }
    public function isValid(): bool
    {
        return !empty($this->data) && !empty($this->extension);
    }

    public function isTooBig(int $maxSize): bool
    {
        if (!isset($this->tmpFile) || !file_exists($this->tmpFile)) {
            // Fallback to base64 calculation if tmpFile not available
            if (empty($this->data)) {
                return false;
            }
            $parts = explode(',', $this->data, 2);
            if (count($parts) !== 2) {
                return false;
            }
            $base64 = $parts[1];
            $decoded = base64_decode($base64, true);
            if ($decoded === false) {
                return false;
            }
            $calculatedSize = strlen($decoded);
            return $calculatedSize > $maxSize;
        }
        // Check actual file size of the encrypted tmpFile
        $actualSize = filesize($this->tmpFile);
        return $actualSize > $maxSize;
    }

    public function jsonSerialize(): array
    {
        return [
            'data' => $this->data,
            'extension' => $this->extension,
            'width' => $this->width,
            'height' => $this->height,
            'size' => $this->size,
            'resolution' => $this->resolution,
            'type' => $this->type,
            // 'device' => $this->device,
            'timestamp' => $this->timestamp,
        ];
    }
}

/**
 * Expected data:
 *
 * {
    "timestamp": "2025-10-18T11:28:34.851Z",
    "extension": "png",
    "resolution": "1200x2080",
    "width": 1200,
    "height": 2080,
    "size": 2586439,
    "type": "auto",
    "device": "desktop",
    "data": "data:image/png;base64,..."
}
 */