<?php

namespace App\Modifiers;

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

class Compressor
{
    public function make(
        $fileName, 
        $compression
    ): array {
        $filePath = Storage::disk('temp')
            ->path($fileName);
        
        $compression = 100 - ($compression == 100 ? 99 : $compression);

        $backgroundImagick = new Imagick($filePath);

        $imagick = new Imagick();
        $imagick->setCompressionQuality($compression);
        $imagick->newPseudoImage(
            $backgroundImagick->getImageWidth(),
            $backgroundImagick->getImageHeight(),
            'canvas:white'
        );
    
        $imagick->compositeImage(
            $backgroundImagick,
            Imagick::COMPOSITE_ATOP,
            0,
            0
        );
        
        $imagick->stripImage();
        $result = $imagick->writeImage($filePath);
        $imagick->clear();
        $imagick->destroy();

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

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

}