<?php

namespace frontend\jobs;

use Yii;
use yii\helpers\{Html, Json, FileHelper};
use yii\base\BaseObject;
use yii\httpclient\Client;
use backend\models\{Galleriesbe,Sysmodels, Categoriesbe, Productsbe, Lookuptablebe, Uploadsbe,};
use yii\imagine\Image;
use Imagine\Gd;
use Imagine\Image\{Box, BoxInterface, Metadata\ExifMetadataReader};

class ImportImages extends BaseObject implements \common\components\Queue\JobInterface
{
    /**
     * Runs Imports from Various Sources.
     *
     * @param [type] $queue
     * @return void
     */
    public function execute($queue)
    {
        $tmp = strtolower(Yii::getAlias('@temp') . "/");
        foreach (Productsbe::find()->all() as $key => $model) {
            $files = FileHelper::findFiles($tmp, ['filter' => function ($tmppath) use ($model) {
                return \str_contains($tmppath, $model->id);
            }]);
            if (is_array($files) && count($files) > 0) {
                $imageData = [];
                foreach ($files as $id => $tmpfile) {
                    echo $tmpfile . PHP_EOL;
                    $path = $model->id;
                    $type = 'Products';
                    $filepath = Yii::getAlias('@uploads') . "/" . strtolower($type) . "/$path/";
                    $urlpath = "/uploads/" . strtolower($type) . "/$path/";
                    //$temp = strtolower(Yii::getAlias('@temp')."/");
                    $file_details = \pathinfo($tmpfile);
                    $filename = str_replace($model->id . '_', '', $file_details['basename']);
                    $fileName = str_replace($model->id . '_', '', $file_details['filename']);
                    //$fileName = str_replace(' ', '_', $model->id).'_'.$file_details['filename'];
                    if (file_exists($tmpfile) == true) {
                        FileHelper::createDirectory($filepath . "original");
                        $file = file_get_contents($tmpfile);
                        $file2 = file_put_contents($filepath . 'original/' . $filename, $file);
                        $newWidth = "1024";
                        $newHeight = "768";
                        $TsavePath = "$filepath/$filename";
                        if (in_array($file_details['extension'], ['jpg', 'jpeg', 'png']) == true) {
                            Image::getImagine()
                                ->open($tmpfile)
                                ->thumbnail(new Box($newWidth, $newHeight))
                                ->save($TsavePath, ['quality' => 70]);
                            $phptype = exif_imagetype($filepath . "original/" . $filename);
                            if ($phptype == IMAGETYPE_JPEG) {
                                $image = imagecreatefromjpeg($filepath . "original/" . $filename);
                                ob_start();
                                \imagejpeg($image, null, 100);
                                $cont =  ob_get_contents();
                                ob_end_clean();
                                \imagewebp(imagecreatefromstring($cont), "$filepath/$fileName.webp");
                            } elseif ($phptype == IMAGETYPE_PNG) {
                                $image = imagecreatefrompng($filepath . "original/" . $filename);
                                if ($image) {
                                    //\imagepng($image, null, 0);
                                    imagepalettetotruecolor($image);
                                    imagealphablending($image, true);
                                    imagesavealpha($image, true);
                                    \imagewebp($image, "$filepath/$fileName.webp");
                                    \imagedestroy($image);
                                }
                            }
                        }
                    }
                    unlink($tmpfile);
                    $convert_image = [
                        'size' => null,
                        'width' => $newWidth,
                        'height' => $newHeight,
                        'webp' => $urlpath . $fileName . ".webp",
                        'filename' => $fileName . ".webp",
                        'original' => $urlpath . "original/" . $filename,
                    ];
                    //$convert_image = self::Convert($filename, 'Products', $model->id);


                    $upload = new Uploadsbe(['id' => Uploadsbe::Tempid()]);
                    $upload->filename = $convert_image['filename'];
                    $upload->filepath = $convert_image['webp'];
                    $upload->ofilepath = $convert_image['original'];
                    $upload->mime = null;
                    $upload->size = $convert_image['size'];
                    $upload->height = $convert_image['height'];
                    $upload->width = $convert_image['width'];
                    $upload->validate();
                    $imageData['main'][] = $upload;
                }
                $model->syncImages($imageData);
                $model->save();
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function getTtr()
    {
        return 6000;
    }

    /**
     * @inheritdoc
     */
    public function canRetry($attempt, $error)
    {
        return $attempt < 3;
    }
}
