<?php

namespace App\Modifiers;

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

class Preferences
{
    public function make($fileName, $preferences)
    {
        $filePath = Storage::disk('temp')
            ->path($fileName);
        $imagick = new Imagick($filePath);

        if (isset($preferences['brightness']) && $preferences['brightness']) {
            $imagick
                ->modulateImage(
                    100 + $preferences['brightness'], 
                    100, 
                    100
                );
        }

        if (isset($preferences['contrast']) && $preferences['contrast']) {
            $imagick
                ->sigmoidalContrastImage(
                    $preferences['contrast'] > 0, 
                    abs($preferences['contrast'] / 4), 
                    0
                );
        }

        if (isset($preferences['gamma']) && $preferences['gamma']) {
            $imagick
                ->gammaImage($preferences['gamma']);
        }

        if (isset($preferences['red']) && $preferences['red']) {
            $red = $this->normalizeLevel($preferences['red']);
            $qrange = $imagick->getQuantumRange();
            $imagick
                ->levelImage(
                    0, 
                    $red, 
                    $qrange['quantumRangeLong'], 
                    Imagick::CHANNEL_RED
                );
        }

        if (isset($preferences['green']) && $preferences['green']) {
            $green = $this->normalizeLevel($preferences['green']);
            $qrange = $imagick
                ->getQuantumRange();
            $imagick
                ->levelImage(
                    0, 
                    $green, 
                    $qrange['quantumRangeLong'], 
                    Imagick::CHANNEL_GREEN
                );
        }

        if (isset($preferences['blue']) && $preferences['blue']) {
            $blue = $this->normalizeLevel($preferences['blue']);
            $qrange = $imagick
                ->getQuantumRange();
            $imagick
                ->levelImage(
                    0, 
                    $blue, 
                    $qrange['quantumRangeLong'], 
                    Imagick::CHANNEL_BLUE
                );
        }

        $result = $imagick->writeImage($filePath);
        $imagick->clear();
        $imagick->destroy();

        if ($result) {
            $toolStats = new ToolStats();
            $toolStats->processNew('preferences');
            return [
                true,
                $fileName
            ];
        }

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

    private function normalizeLevel(
        int $level
    ): int {
        return $level > 0 
            ? intval(round($level / 5)) 
            : intval(round(($level + 100) / 100));
    }

}