<?php

/**
 * 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);
        $greagwar_image->setCacheDir(Config::get('PATH_WEB_ROOT') . DIRECTORY_SEPARATOR . self::$dir_image_cache);
        return $greagwar_image;
    }

    public static function getFilePath($image)
    {
        return 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());
        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);
        $image->variants[$size] = $image_variant;
        if (Config::get('PYTHON_PIL_RESIZE')) {
            $script_file_path = Config::get('PYTHON_PIL_RESIZE')->script_file_path;
            $pil_options = isset(Config::get('PYTHON_PIL_RESIZE')->pil_options) ? ' ' . implode(' ', Config::get('PYTHON_PIL_RESIZE')->pil_options) : '';
            ob_start();
            exec($script_file_path
                . (($size_parts[0])?' --width=' . $size_parts[0]:'')
                . (($size_parts[1])?' --height=' . $size_parts[1]:'')
                . $pil_options
                . ' ' . self::getFilePath($image)
                . ' ' . self::getFilePath($image_variant));
            ob_clean();
        }
        if ($image->getWatermark($size) && Config::get('PYTHON_PIL_PASTE')) {
            $script_file_path = Config::get('PYTHON_PIL_PASTE')->script_file_path;
            $pil_options = (isset(Config::get('PYTHON_PIL_PASTE')->pil_options) && Config::get('PYTHON_PIL_PASTE')->pil_options) ? ' ' . implode(' ', Config::get('PYTHON_PIL_PASTE')->pil_options) : '';
            ob_start();
            exec($script_file_path
                . $pil_options
                . ' ' . self::getFilePath($image_variant)
                . ' ' . Config::get('PATH_WEB_ROOT') . '/' . $image->getWatermark($size));
            ob_clean();
        }
    }

    /**
     * @param $image ImageVariant|Image
     * @param $tmp_file_path string|GreagwarImage
     * @param null $width
     * @param null $height
     * TODO: Сделать возможность передавать параметры для метода _resize()
     */
    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);
        }
        if ($width || $height) {
            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);
            }
        }
        $image->type = $greagwar_image->guessType();
        $file_path = $greagwar_image->cacheFile($image->type, $quality = 100, true);
        $image->size = filesize($file_path);
        $path_parts = pathinfo($file_path);
        $image->path = preg_replace('#^' . Config::get('PATH_WEB_ROOT') . '/#', '', $path_parts['dirname']);
        $image->filename = $path_parts['basename'];
        $image->width = $greagwar_image->width();
        $image->height = $greagwar_image->height();
        unset($greagwar_image);
    }

    /**
     * @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);
            }
        }
    }
}