<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessFaceSwap implements ShouldQueue
{
    use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $params;

    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 3600;

    /**
     * Indicate if the job should be marked as failed on timeout.
     *
     * @var bool
     */
    public $failOnTimeout = false;

    /**
     * Create a new job instance.
     *
     * @param $params
     */
    public function __construct($params)
    {
        $this->onQueue(config('queue.connections.redis.queue'));
        $this->params = $params;
    }

    /**
     * @return bool
     */
    public function isFailOnTimeout(): bool
    {
        return $this->failOnTimeout;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $sourceImg = $this->params['source'];
            $targetImg = $this->params['target'];
            $fileName = $this->params['key'] . ".jpg";
            $resultImg = public_path('uploads/files/') . "__" . $fileName;
            $exportImg = public_path('uploads/files/') . $fileName;

            //$resultImg = public_path('uploads/files/') . "__" . $key . ".jpg";

            //Config Python ENV
            //cd ~ && mkdir virtual_env
            ///usr/bin/python3.10 -m venv ~/virtual_env/venv_with_python3.10
            //source ~/virtual_env/venv_with_python3.10/bin/activate

            $appEnv = config('app.env');
            $pythonPath = config('faceswap.python_path');
            $faceSwapPath = config('faceswap.faceswap_app_path');

            $gpuProvider = " --execution-provider cuda";
            if ($appEnv == "local") {
                //$gpuProvider = " --execution-provider cuda"; //GPU Cuda | CPU
                $gpuProvider = " --execution-provider cpu"; //GPU Cuda | CPU
            }

            $command = $pythonPath . "python " . $faceSwapPath . "run.py -t " . $targetImg . " -s " . $sourceImg . " -o " . $resultImg . $gpuProvider . " --frame-processor face_swapper face_enhancer --temp-frame-quality 100 --max-memory 10";
            system($command);
            if (file_exists($resultImg)) rename($resultImg, $exportImg);
        } catch (\Exception $exception) {
            logger("Progress faceswap image error: " . $exception->getMessage());
        }
    }
}
