<?php

namespace App\Classes;

use App\Models\User;
use App\Models\Config;
use App\Models\Optimer;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Spatie\ImageOptimizer\OptimizerChain;
use Spatie\ImageOptimizer\Optimizers\Svgo;
use Spatie\ImageOptimizer\Optimizers\Cwebp;
use Spatie\ImageOptimizer\Optimizers\Gifsicle;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;

class APIWasabiStorage
{
    public function wasabiFunction($request)
    {
        // Authorization
        $header = $request->header('Authorization');
        $userId = User::where('api_key', $header)->where('status', 1)->first();

        // Get plan details
        $plan_details = json_decode($userId->plan_details);

        // Request file
        $files = $request->images;
        $compressionRatio = abs($request->compression_ratio);

        // Check loop
        for ($i = 0; $i < count($files); $i++) {

            // Check extension
            if (
                $request->images[$i]->extension() == "svg" || $request->images[$i]->extension() == "jpg" || $request->images[$i]->extension() == "jpeg" || $request->images[$i]->extension() == "png" || $request->images[$i]->extension() == "webp" || $request->images[$i]->extension() == "gif" ||
                $request->images[$i]->extension() == "SVG" || $request->images[$i]->extension() == "JPG" || $request->images[$i]->extension() == "JPEG" || $request->images[$i]->extension() == "PNG" || $request->images[$i]->extension() == "WEBP" || $request->images[$i]->extension() == "GIF"
            ) {

                // Generate Name, width, height
                $imageName = random_int(000000000000001, 99999999999999) . '.' . $request->images[$i]->extension();
                $width = 0;
                $height = 0;

                // Get extension, original name, MIME type
                $extension = $files[$i]->getClientOriginalExtension();
                $originalname = $files[$i]->getClientOriginalName();
                $mimetype = $files[$i]->getClientMimeType();

                // Move original image
                $originalPath = $files[$i]->move(public_path('/storage/files/' . $userId->id . '/'), $imageName);

                // Create optimize image folder
                $optimizePath = public_path() . '/storage/files/' . $userId->id . '/optimize/';
                File::makeDirectory($optimizePath, 0777, true, true);

                // Move image original folder to optimize folder
                File::copy(public_path('/storage/files/' . $userId->id . '/' . $imageName), $optimizePath . $imageName);

                // Get image size in kb
                $imgsizes = $originalPath->getSize();

                // Get image width and height
                if ($extension != "svg" || $extension != "SVG") {
                    // $data = getimagesize($originalPath);
                    // $width = $data[0];
                    // $height = $data[1];
                    $width = 500;
                    $height = 500;
                }

                // Upload wasabi S3
                $path = Storage::disk('wasabi')->put('files/' . $userId->id . '/' . $imageName, file_get_contents('storage/files/' . $userId->id . '/' . $imageName));
                $request->merge([
                    'path' => $path
                ]);

                // Get original AWS path
                $AWSOriginalPath = $request->only('path', 'title');

                $status = false;
                $optimizerChain = "";

                // Optimize Path (JPG)
                if ($extension == "jpg" || $extension == "jpeg" || $extension == "JPG" || $extension == "JPEG" && $plan_details->jpg == 1) {
                    $optimizerChain = (new OptimizerChain)
                        ->addOptimizer(new Jpegoptim([
                            '-m' . $compressionRatio, // set maximum quality to 85%
                            '--strip-all',  // this strips out all text information such as comments and EXIF data
                            '--all-progressive'  // this will make sure the resulting image is a progressive one
                        ]));

                    $status = true;
                }

                // Optimize Path (PNG)
                if ($extension == "png" || $extension == "PNG" && $plan_details->png == 1) {
                    $optimizerChain = (new OptimizerChain)
                        ->addOptimizer(new Pngquant([
                            '--force' // required parameter for this package
                        ]));

                    $status = true;
                }

                // Optimize Path (SVG)
                if ($extension == "svg" || $extension == "SVG" && $plan_details->svg == 1) {
                    $optimizerChain = (new OptimizerChain)
                        ->addOptimizer(new Svgo([
                            '--disable={cleanupIDs,removeStyleElement, removeViewBox}', // disabling because it is know to cause 
                            '--enable={removeTitle,collapseGroups,convertPathData,removeDimensions,removeStyleElement,removeScriptElement,removeEmptyContainers}',
                        ]));

                    $status = true;
                }

                // Optimize Path (GIF)
                if ($extension == "gif" || $extension == "GIF" && $plan_details->gif == 1) {
                    $optimizerChain = (new OptimizerChain)
                        ->addOptimizer(new Gifsicle([
                            '-b', // required parameter for this package
                            '-0' // this produces the slowest but best results
                        ]));

                    $status = true;
                }
                // Optimize Path (WEBP)
                if ($extension == "webp" || $extension == "WEBP" && $plan_details->webp == 1) {
                    $optimizerChain = (new OptimizerChain)
                        ->addOptimizer(new Cwebp([
                            '-m 6', // for the slowest compression method in order to get the best compression.
                            '-pass 10', // for maximizing the amount of analysis pass.
                            '-mt', // multithreading for some speed improvements.
                            '-q ' . $compressionRatio, //quality factor that brings the least noticeable changes.
                        ]));

                    $status = true;
                }

                // Check plan extension
                if ($status == true) {
                    // Optimize
                    $optimizerChain->optimize('storage/files/' . $userId->id . '/optimize/' . $imageName);

                    // Get optimize image
                    $optimizeImage = file_get_contents('storage/files/' . $userId->id . '/optimize/' . $imageName);

                    // Upload wasabi S3
                    $path = Storage::disk('wasabi')->put('files/' . $userId->id . '/optimize/' . $imageName, $optimizeImage);
                    $request->merge([
                        'path' => $path
                    ]);

                    // Get optimize AWS path
                    $AWSOptimizePath = $request->only('path', 'title');

                    // Get optimize image size
                    $OptimizeAWSPathSize = filesize($optimizePath . $imageName);

                    // Save Optimer
                    $optimer = new Optimer();
                    $optimer->optimer_id = random_int(000000000000001, 99999999999999);
                    $optimer->uploaded_by = $userId->id;
                    $optimer->disk = 'wasabi';
                    $optimer->name = $originalname;
                    $optimer->mime = $mimetype;
                    $optimer->extension = $extension;
                    $optimer->width = $width;
                    $optimer->height = $height;
                    $optimer->actual_image = Storage::disk('wasabi')->url('.') . "files/" . $userId->id . '/' . $imageName;
                    $optimer->optimized_image = Storage::disk('wasabi')->url('.') . "files/" . $userId->id . '/optimize/' . $imageName;
                    $optimer->cdn_url = Storage::disk('wasabi')->url('.') . "files/" . $userId->id . '/optimize/' . $imageName;
                    $optimer->actual_image_size = $imgsizes;
                    $optimer->optimized_image_size = $OptimizeAWSPathSize;
                    $optimer->save();

                    $this->status = true;
                    $this->media_url[$i] = Storage::disk('wasabi')->url('.') . "files/" . $userId->id . '/optimize/' . $imageName;

                    return $this;
                } else {
                    $this->status = "unsupported";
                    $this->media_url[$i] = "";

                    return $this;
                }
            } else {
                $this->status = false;
                $this->media_url[$i] = "";

                return $this;
            }
        }
    }
}
