<?php
namespace dimti\Image;

/**
 * Class Upload
 * @version 0.2
 */
abstract class Upload
{
    public static $dir_image_cache = 'media/cache/images';

    public static function &getGreagwarImage($file_path)
    {
        $greagwar_image = new \GreagwarImage($file_path);
	    $config_upload = \Majestic\Config::get('Upload');
	    $dir_image_cache = $config_upload ? $config_upload->dir_image_cache : self::$dir_image_cache;
        $greagwar_image->setCacheDir(\Majestic\Config::get('PATH_WEB_ROOT') . DIRECTORY_SEPARATOR . $dir_image_cache);
        return $greagwar_image;
    }

    public static function getFilePath($image)
    {
        return \Majestic\Config::get('PATH_WEB_ROOT') . DIRECTORY_SEPARATOR . $image->path . DIRECTORY_SEPARATOR . $image->filename;
    }

    /**
     * @param $class string|Image
     * @param $file array (ex. ['tmp_name' => '...', 'name' => '...', 'error' => '...'])
     * @param $force_create_variants bool
     * @return Image
     * @throws ErrorException
     * TODO: Рефакторинг: убрать параметр $force_create_variants?
     */
    public static function image($class, $file, $force_create_variants = true)
    {
        /**
         * @var $image Image
         */
        if (is_null($class) || $class == '') {
            throw new \ErrorException('Class not defined.');
        }
        if (!is_object($class) && !class_exists($class)) {
            throw new \ErrorException('Class "' . $class . '" not exists.');
        }
        Image::checkSubClass($class);
        if (isset($file['error']) && $file['error'] != 0) {
            return false;
        }
        $image = is_object($class) ? $class : new $class;
        $image->original_filename = $file['name'];
        self::saveImage($image, $file['tmp_name'], $class::getMaxWidth(), $class::getMaxHeight());
        self::defineSizeWidthAndHeight($image);
        if ($force_create_variants) {
            $sizes = $image->getSizes();
            foreach ($sizes as $size) {
                self::imageVariant($image, $size);
            }
        }
        return $image;
    }

    /**
     * @param $image Image
     * @param $size string @ex '1200x960'
     * @param $greagwar_image \GreagwarImage @deprecated
     */
    public static function imageVariant($image, $size, $greagwar_image = null)
    {
        unset($greagwar_image);
        $image_variant = new ImageVariant();
        $size_parts = explode('x', $size);
        self::saveImage($image_variant, self::getFilePath($image), $size_parts[0] ? : null, $size_parts[1] ? : null);
	    if (\Majestic\Config::get('PYTHON_PIL_PASTE') &&
            method_exists($image, 'getWatermark') &&
	        $image->getWatermark($size)
	    ) {
		    $script_file_path = \Majestic\Config::get('PYTHON_PIL_PASTE')->script_file_path;
		    $pil_options = (isset(\Majestic\Config::get('PYTHON_PIL_PASTE')->pil_options) && \Majestic\Config::get('PYTHON_PIL_PASTE')->pil_options) ? ' ' . implode(' ', \Majestic\Config::get('PYTHON_PIL_PASTE')->pil_options) : '';
            ob_start();
            $code = null;
            $command = $script_file_path
                . $pil_options
                . ' ' . self::getFilePath($image_variant)
                . ' ' . \Majestic\Config::get('PATH_WEB_ROOT') . '/' . $image->getWatermark($size);
		    passthru('exec 2>&1; ' . $command, $code);
            if ($code !== 0) {
                throw new \ErrorException('Command PYTHON_PIL_PASTE exit with code "' . $code . '": ' . $command . PHP_EOL . 'Std out: ' . ob_get_clean() );
            }
            ob_end_clean();
	    }
	    self::defineSizeWidthAndHeight($image_variant);
        $image->variants[$size] = $image_variant;
    }

    /**
     * @param $image ImageVariant|Image
     * @param $tmp_file_path string|\GreagwarImage
     * @param null $width
     * @param null $height
     * TODO: Возможно, стоит искоренить GreagwarImage
     */
    public static function saveImage($image, $tmp_file_path , $width = null, $height = null)
    {
        if (is_object($tmp_file_path)) {
            /**
             * @deprecated
             */
            $greagwar_image = $tmp_file_path;
        } else {
            $greagwar_image = self::getGreagwarImage($tmp_file_path);
        }

	    $image->type = $greagwar_image->guessType();

	    if (!Image::getIsSubClass($image)) {
		    if ( !( ImageVariant::getIsClass( $image ) ) && Image::getIsSubClass( $image ) ) {
			    $greagwar_image->resize( $width, $height, 0xffffff, $force = false, $rescale = false, $crop = true );
		    } else {
			    $greagwar_image->resize( $width, $height, 0xffffff, $force = false, $rescale = false, $crop = false );
		    }
	    }

	    $hash = $greagwar_image->getHash($image->type, $quality = 100);

	    $file_path = $greagwar_image->generateFileFromhash($hash) . '.' . $image->type;

	    if (Image::getIsSubClass($image)) {
		    if (is_uploaded_file($tmp_file_path)) {
			    move_uploaded_file($tmp_file_path, $file_path);
		    } else {
			    copy($tmp_file_path, $file_path);
		    }
	    } else {
		    if (\Majestic\Config::get('PYTHON_PIL_RESIZE')) {
			    $script_file_path = \Majestic\Config::get( 'PYTHON_PIL_RESIZE' )->script_file_path;
                
			    $pil_options      = isset( \Majestic\Config::get( 'PYTHON_PIL_RESIZE' )->pil_options ) ? ' ' . implode( ' ', \Majestic\Config::get( 'PYTHON_PIL_RESIZE' )->pil_options ) : '';

			    //            ob_start();

			    $code = null;

			    $command = $script_file_path
			               . ( ( $width ) ? ' --width=' . $width : '' )
			               . ( ( $height ) ? ' --height=' . $height : '' )
			               . $pil_options
			               . ' ' . $tmp_file_path
			               . ' ' . $file_path;

                ob_start();

			    passthru( 'exec 2>&1; ' . $command, $code );

			    if ($code !== 0) {
				    throw new \ErrorException('Command PYTHON_PIL_RESIZE exit with code "' . $code . '": ' . $command . PHP_EOL . 'Std out: ' . ob_get_clean() );
			    }
			    ob_end_clean();
		    } else {
			    if ($width || $height) {
				    $file_path = $greagwar_image->cacheFile($image->type, $quality = 100, true);
			    }
		    }
	    }

        $path_parts = pathinfo($file_path);

        $image->path = preg_replace('#^' . \Majestic\Config::get('PATH_WEB_ROOT') . '/#', '', $path_parts['dirname']);

        $image->filename = $path_parts['basename'];

	    self::defineSizeWidthAndHeight($image);

        unset($greagwar_image);
    }

    private static function defineSizeWidthAndHeight($image)
    {
        $file_path = self::getFilePath($image);
        $imagesize = getimagesize($file_path);
        $image->width = $imagesize[0];
        $image->height = $imagesize[1];
        $image->size = filesize($file_path);
    }

    /**
     * @param $image
     * @param string $value
     * @deprecated
     */
    public static function brightnessContrast($image, $value = '0x7')
    {
        $file_path = self::getFilePath($image);
        $output = shell_exec("convert {$file_path} -brightness-contrast {$value} {$file_path} 2>&1");
        if (isset($output) && $output) {
            if (class_exists('ErrorMessage')) {
                \ErrorMessage::log($output);
            }
        }
    }
}