<?php

namespace Fifa\ConnectId\Sdk\Model\DataStandard;

use Fifa\ConnectId\Sdk\Util\File;
use InvalidArgumentException;

/**
 * Class PictureEmbedded
 * @package Fifa\ConnectId\Sdk\Model\DataStandard
 */
class PictureEmbedded
{
    /**
     * @var string
     */
    const CONTENT_TYPE_KEY = 'xmime:contentType';

    /**
     * @var string[]
     */
    public $_attributes;

    /**
     * @var string
     * @required
     */
    public $_content;

    /**
     * @param string $base64Content
     * @param string|null $contentType
     * @return PictureEmbedded
     *
     * @throws InvalidArgumentException
     */
    public static function createFromBase64String(string $base64Content, ?string $contentType = 'image/jpeg'): PictureEmbedded
    {
        return new self($base64Content, $contentType);
    }

    /**
     * @param string $filePath
     * @return PictureEmbedded
     *
     * @throws InvalidArgumentException
     */
    public static function createFromLocalPath(string $filePath): PictureEmbedded
    {
        $fileContent = File::getContents($filePath);
        $imageInfo = getimagesizefromstring($fileContent);
        $base64encoded = base64_encode($fileContent);

        return self::createFromBase64String($base64encoded, $imageInfo['mime']);
    }

    /**
     * PictureEmbedded constructor - blocked by private visibility
     *
     * @param string $base64content
     * @param string|null $contentType
     *
     * @throws InvalidArgumentException
     */
    private function __construct(string $base64content, ?string $contentType)
    {
        $this->setContent($base64content);
        if ($contentType !== null) {
            $this->_attributes[self::CONTENT_TYPE_KEY] = $contentType;
        }
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return sprintf('Content: %s, Type: %s', $this->_content, $this->_attributes[self::CONTENT_TYPE_KEY]);
    }

    /**
     * @param string $base64Content
     * @throws InvalidArgumentException
     */
    private function setContent(string $base64Content)
    {
        $decoded = base64_decode($base64Content);
        $imageInfo = getimagesizefromstring($decoded);

        if (!$imageInfo) {
            throw new InvalidArgumentException('Given content is not correct base64 encoded image.');
        }

        $this->_content = $base64Content;
    }
}