<?php

namespace App\Repositories\Core;

use Barryvdh\DomPDF\Facade\Pdf as DomPDF;
use Barryvdh\Snappy\Facades\SnappyPdf;
use GravityMedia\Ghostscript\Ghostscript;
use Mpdf\Mpdf;
use Symfony\Component\Process\Process;

class PDF
{
    public function convertView($view, $data, $filename)
    {
        try {
            Browsershot::html(view($view, $data)->render())
                ->noSandbox()
                ->waitUntilNetworkIdle()
                ->format('A4')
                ->showBackground()
                ->savePdf('temp.pdf');

            $postRoute = URL::signedRoute('orderinvoices.store', ['order' => $this->order]);
            Http::attach('invoice', file_get_contents('temp.pdf'), $filename)
                ->post($postRoute)
                ->throw();
        } catch (\Exception $exception) {
            Log::error($exception);
        }
    }

    public static function view($view, $data, $filename = 'file.pdf')
    {
        \Debugbar::disable();
        $pdf = DomPDF::loadView($view, $data);

        return $pdf->download($filename);
    }

    public static function convertHTML($html)
    {
        $mpdf = new Mpdf();
        $mpdf->WriteHTML($html);

        return $mpdf->Output();
    }

    public static function convertURL($url)
    {
        $pdf = SnappyPdf::loadFile($url);

        return $pdf->download('invoice.pdf');
    }

    public static function convertIfNeeded($filename)
    {
        if (self::getVersion($filename) > 1.4) {
            self::downgrade2($filename);
        }
    }

    public static function getVersion($filename)
    {
        $pdf = fopen($filename, 'r');
        if ($pdf) {
            $line_first = fgets($pdf);
            fclose($pdf);
        } else {
            echo 'error opening the file.';
        }
        preg_match_all('!\d+!', $line_first, $matches);
        $version = implode('.', $matches[0]);

        return (float) $version;
    }

    public static function downgrade($filename)
    {
        $new_filename = $filename.'-temp';
        $ghostscript = new Ghostscript([
            'quiet' => false,
        ]);

        $device = $ghostscript->createPdfDevice($new_filename);
        $device->setCompatibilityLevel(1.4);

        // dump($device);
        $process = $device->createProcess($filename);
        // dump($process);
        // echo '$ ' . $process->getCommandLine() . PHP_EOL;
        // exit;
        $process->run(function ($type, $buffer) {
            if ($type === Process::ERR) {
                throw new \RuntimeException($buffer);
            }
            // print $buffer;
        });

        unlink($filename);
        rename($new_filename, $filename);
    }

    public static function downgrade2($filename)
    {
        $new_filename = $filename.'-temp';
        shell_exec('gs -dBATCH -dCompatibilityLevel=1.4 -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="'.$new_filename.'" "'.$filename.'"');
        unlink($filename);
        rename($new_filename, $filename);
    }
}
