<?php

namespace App\Soshot;

use App\Soshot\GetThumb;
use Embed\Embed;
use App\Utils\ConvertToPng;

class GetOg extends GetThumb {

    public function makeOg() {

        if (!is_dir($this->filePath)) {
            mkdir($this->demande->filePath);
        }

        try {
            $embed = new Embed();
            $info = $embed->get($this->demande->url);

            if (!is_null($info->image)) {
                if (!$image = file_get_contents($info->image)) {
                    copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
                    $this->db->addUpdate(2);
                    return true;
                }
            } else {
                copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
                $this->db->addUpdate(2);
                return true;
            }

            if (empty($image)) {
                copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
                $this->db->addUpdate(2);
                return true;
            }

            file_put_contents($this->demande->requestImg, $image);

            if (in_array(mime_content_type($this->demande->requestImg), ['image/jpg', 'image/jpeg', 'image/bmp', 'image/webp'])) {
                ConvertToPng::convertToPng($this->demande);
            }
        } catch (\Exception $e) {
            copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
            $this->db->addUpdate(2);
        }
        if (!is_file($this->demande->requestImg)) {
            copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
            $this->db->addUpdate(2);
        } else {
            $this->db->addUpdate(1);
        }
    }

    public function show() {
        if (file_exists($this->requestImg) && $this->type === 'og') {
        } else {
            $this->makeOg();
        }

        //echo '<img src="data:' . mime_content_type($this->requestImg) . ';base64,' . base64_encode(file_get_contents($this->requestImg)) . '">';
        header("Content-type: " . mime_content_type($this->requestImg));
        header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
        echo file_get_contents($this->requestImg);
        exit();
    }
}
