<?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 DownloadImages extends BaseObject implements \common\components\Queue\JobInterface
{
    /**
     * Runs Imports from Various Sources.
     *
     * @param [type] $queue
     * @return void
     */
    public function execute($queue)
    {
        foreach (Productsbe::find()->where(['is','imageData', null])->all() as $key => $model) {
            $importdata = json_decode($model->importdata, 1);
            if (empty($importdata['product_images1']) == false) {
                $exp = explode('.', $importdata['product_images1']);
                $code = $exp[0];
                $images = ["https://foodb.ca/system/foods/pictures/$code/full/" . $importdata['product_images1']];
                $imageData = [];
                $path = $model->id;
                foreach ($images as $image) {
                    echo $image . PHP_EOL;
                    $tmp = strtolower(Yii::getAlias('@temp') . "/");
                    $url = $image;
                    $urlp = explode('/', $url);
                    $filename = str_replace(' ', '_', $model->id) . '_' . $urlp[array_key_last($urlp)];
                    $client = new Client([
                        'transport' => yii\httpclient\CurlTransport::class,
                    ]);
                    $fh = fopen($tmp . $filename, 'w');
                    $response = $client->createRequest()
                        ->setMethod('GET')
                        ->setUrl($url)
                        ->setOptions(['sslVerifyPeer' => false])
                        ->setOutputFile($fh)
                        ->send();
                    echo $response->statuscode . PHP_EOL;
                    if ($response->statuscode == 200) {
                        $stop = false;
                    } else {
                        unlink($tmp . $filename);
                        $last4 = \substr("https://foodb.ca/system/foods/pictures/$code/full/" . $importdata['product_images1'], -4, 4);
                        $l4 = $last4 == '.png' ? '.jpg' : '.png';
                        $url = str_replace($last4, $l4, "https://foodb.ca/system/foods/pictures/$code/full/" . $importdata['product_images1']);
                        $urlp = explode('/', $url);
                        $filename = str_replace(' ', '_', $model->id) . '_' . $urlp[array_key_last($urlp)];
                        $client = new Client([
                            'transport' => yii\httpclient\CurlTransport::class,
                        ]);
                        $fh = fopen($tmp . $filename, 'w');
                        $response = $client->createRequest()
                            ->setMethod('GET')
                            ->setUrl($url)
                            ->setOptions(['sslVerifyPeer' => false])
                            ->setOutputFile($fh)
                            ->send();
                        echo $response->statuscode . PHP_EOL;
                        if ($response->statuscode == 200) {
                            $stop = false;
                        } else {
                            unlink($tmp . $filename);
                            $code = intval(substr($model->stock_code, -4, 4));
                            $url = "https://foodb.ca/system/foods/pictures/$code/full/$code.png";
                            $urlp = explode('/', $url);
                            $filename = str_replace(' ', '_', $model->id) . '_' . $urlp[array_key_last($urlp)];
                            $client = new Client([
                                'transport' => yii\httpclient\CurlTransport::class,
                            ]);
                            $fh = fopen($tmp . $filename, 'w');
                            $response = $client->createRequest()
                                ->setMethod('GET')
                                ->setUrl($url)
                                ->setOptions(['sslVerifyPeer' => false])
                                ->setOutputFile($fh)
                                ->send();
                            echo $response->statuscode . PHP_EOL;
                            if ($response->statuscode == 404) {
                                unlink($tmp . $filename);

                                $last4 = \substr("https://foodb.ca/system/foods/pictures/$code/full/$code.png", -4, 4);
                                $l4 = $last4 == '.png' ? '.jpg' : '.png';
                                $url = str_replace($last4, $l4, "https://foodb.ca/system/foods/pictures/$code/full/$code.png");
                                $urlp = explode('/', $url);
                                $filename = str_replace(' ', '_', $model->id) . '_' . $urlp[array_key_last($urlp)];
                                $client = new Client([
                                    'transport' => yii\httpclient\CurlTransport::class,
                                ]);
                                $fh = fopen($tmp . $filename, 'w');
                                $response = $client->createRequest()
                                    ->setMethod('GET')
                                    ->setUrl($url)
                                    ->setOptions(['sslVerifyPeer' => false])
                                    ->setOutputFile($fh)
                                    ->send();
                                echo $response->statuscode . PHP_EOL;
                                if ($response->statuscode == 200) {
                                    $stop = false;
                                } else {
                                    unlink($tmp . $filename);
                                    $stop = true;
                                }
                            }
                            $stop = false;
                        }
                    }
                    /*
                    if ($stop == false) {
                        $type = 'Products';
                        $filepath = Yii::getAlias('@uploads')."/".strtolower($type)."/$path/";
                        $urlpath = "/uploads/".strtolower($type)."/$path/";
                        $temp = strtolower(Yii::getAlias('@temp')."/");
                        $file_details = \pathinfo($temp.$filename);
                        $filename = str_replace(' ', '_', $model->id).'_'.$file_details['basename'];
                        $filename = str_replace(' ', '_', $model->id).'_'.$file_details['filename'];
                        if (file_exists($temp.$filename) == true)  {
                            FileHelper::createDirectory($filepath."original");
                            $file = file_get_contents($temp.$filename);
                            $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($temp."/".$filename)
                                    ->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();
                                }elseif ($phptype == IMAGETYPE_PNG) {
                                    $image = imagecreatefrompng($filepath."original/".$filename);
                                    if ($image) {
                                        ob_start();
                                        \imagepng($image, null, 100);
                                        $cont=  ob_get_contents();
                                        ob_end_clean();
                                    }
                                }
                                if ($cont) {
                                    \imagewebp(imagecreatefromstring($cont),"$filepath/$fileName.webp");
                                }
                            }

                        }
                        unlink($temp.$filename);
                        $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;
    }
}
