<?php

namespace App\Helpers\Image;

use PHPImageWorkshop\Core\ImageWorkshopLayer;
use PHPImageWorkshop\Exception\ImageWorkshopException;
use PHPImageWorkshop\ImageWorkshop as BaseImageWorkshop;

class ImageWorkshop extends BaseImageWorkshop
{

    /**
     * Initialize a layer from a given image path
     *
     * From an upload form, you can give the "tmp_name" path
     *
     * @param string $path
     * @param bool   $fixOrientation
     *
     * @return ImageWorkshopLayer
     */
    public static function initFromPath($path, $fixOrientation = false)
    {
        if (false === filter_var($path, FILTER_VALIDATE_URL) && !file_exists($path)) {
            throw new ImageWorkshopException(sprintf('File "%s" not exists.', $path), static::ERROR_IMAGE_NOT_FOUND);
        }

        if (false === ($imageSizeInfos = @getImageSize($path))) {
            throw new ImageWorkshopException('Can\'t open the file at "' . $path . '" : file is not readable, did you check permissions (755 / 777) ?', static::ERROR_NOT_READABLE_FILE);
        }

        $mimeContentType = explode('/', $imageSizeInfos['mime']);
        if (!$mimeContentType || !isset($mimeContentType[1])) {
            throw new ImageWorkshopException('Not an image file (jpeg/png/gif) at "' . $path . '"', static::ERROR_NOT_AN_IMAGE_FILE);
        }

        $mimeContentType = $mimeContentType[1];
        $exif = array();

        switch ($mimeContentType) {
            case 'jpeg':
                $image = \imageCreateFromJPEG($path);
                if (false === ($exif = @read_exif_data($path))) {
                    $exif = array();
                }
                break;

            case 'gif':
                $image = \imageCreateFromGIF($path);
                break;

            case 'png':
                $image = \imageCreateFromPNG($path);
                break;

            default:
                throw new ImageWorkshopException('Not an image file (jpeg/png/gif) at "' . $path . '"', static::ERROR_NOT_AN_IMAGE_FILE);
                break;
        }

        if (false === $image) {
            throw new ImageWorkshopException('Unable to create image with file found at "' . $path . '"');
        }

        $layer = new ImageWorkshopLayer($image, $exif);

        if ($fixOrientation) {
            $layer->fixOrientation();
        }

        return $layer;
    }
}
