<?php

namespace App\Http\Controllers;

use App\Helpers\Image\Watermark;
use Illuminate\Http\Request;
use App\Helpers\Image\ImageWorkshop;
use Screen\Capture;

class PrintScreenController extends Controller
{
    public function generatePrintScreenImage(Capture $screenCapture, Request $request, $optionsBase64)
    {
        $options = json_decode(base64_decode($optionsBase64));

        $dirPath = public_path() . "/images/printscreen";
        $filename = md5($optionsBase64) . ".jpg";
        $userAgentString = isset($options->userAgent) && $options->userAgent ? $options->userAgent : $request->server->get('HTTP_USER_AGENT');

        $screenCapture->output->setLocation($dirPath);
        $screenCapture->setUserAgentString($userAgentString);

        $screenCapture->setWidth($options->width);
        if ($options->height) {
            $screenCapture->setHeight($options->height);
            $screenCapture->setClipWidth($options->width);
            $screenCapture->setClipHeight($options->height);
        } else {
            $screenCapture->setHeight(600);
        }

        if ($options->bgColor) {
            $screenCapture->setBackgroundColor($options->bgColor);
        }

        $screenCapture->setUrl($options->url);
        $screenCapture->save($filename);

        $image = ImageWorkshop::initFromPath($dirPath . DIRECTORY_SEPARATOR . $filename);

        Watermark::apply($dirPath, $filename);

        return response()->json([
            'status'  => true,
            'image'   => [
                'src'    => asset('images/printscreen/' . $filename),
                'width'  => $image->getWidth(),
                'height' => $image->getHeight(),
            ],
            'options' => $options,
        ]);
    }
}
