<?php

namespace Modules\Base\Listeners;

class ProcessUploadImage
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param object $event
     *
     * @return void
     */
    public function handle($event)
    {
        $file = $event->file;
        $config = config('upload.'.$file->type, []);

        if (!isset($config['image_processor']) || !$config['image_processor']) {
            return;
        }

        $root = config('filesystems.disks.'.$config['filesystem'].'.root', false);
        $img_file = $root ? $root.'/'.$file->path : get_file_url($file->path, $file->type);
        $img = \Image::make($img_file);

        $processors = explode('|', $config['image_processor']);

        foreach ($processors as $processor) {
            $this->process($img, $processor);
        }
        $img->save();

        clearstatcache();
        $file->size = filesize($img_file);
        $file->save();
    }

    protected function process($img, $processor)
    {
        $info = explode(':', $processor);

        list($method, $args) = count($info) > 1 ? [$info[0], explode(',', $info[1])] : [$info[0], []];

        array_walk($args, function (&$val) {
            if ($val == 'null') {
                $val = null;
            }

            if (substr($val, 0, 11) === 'constraint=') {
                $param = substr($val, 11);
                $val = function ($constraint) use ($param) {
                    $funcs = explode('&', $param);
                    foreach ($funcs as $func) {
                        call_user_func([$constraint, $func]);
                    }
                };
            }
        });

        call_user_func_array([$img, $method], $args);
    }
}
