<?php

namespace App\Modifiers;

use Imagick;
use Illuminate\Support\Facades\Storage;
use App\Models\ToolStats;

class Effects
{
    public function make($fileName, $effect)
    {
        $filePath = Storage::disk('temp')
            ->path($fileName);

        $imagick = new Imagick($filePath);

        if (isset($effect['grayscale']) && $effect['grayscale']) {
            $imagick->modulateImage(100, 0, 100);
        }

        if (isset($effect['blur']) && $effect['blur']) {
            $imagick->blurImage(1 * 6, 0.5 * 6);
        }

        if (isset($effect['invert']) && $effect['invert']) {
            $imagick->negateImage(false);
        }

        if (isset($effect['pixelation']) && $effect['pixelation']) {

            $width = $imagick->getImageWidth();
            $height = $imagick->getImageHeight();

            $imagick->scaleImage(
                (int) round(max(1, $width / 12)),
                (int) round(max(1, $height / 12))
            );
            $imagick->scaleImage($width, $height);
        }

        if (isset($effect['reduce']) && $effect['reduce']) {
            if (10 <= $imagick->getImageColors()) {
                $imagick->quantizeImage(
                    10,
                    $imagick->getImageColorspace(),
                    0,
                    false,
                    false
                );
            }
        }

        $result = $imagick->writeImage($filePath);
        $imagick->clear();
        $imagick->destroy();
        
        if ($result) {
            $toolStats = new ToolStats();
            $toolStats->processNew('effects');
            return [
                true,
                $fileName
            ];
        }

        return [
            false,
            __('lang.file_effect_error')
       ];
    }

}