<?php

namespace App\Soshot;

use App\Soshot\GetThumb;
use App\Utils\ConvertIco;
use Embed\Embed;
use Zebra_Image;

class GetFav extends GetThumb {

    public function makeFavicon() {

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

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

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

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

            $realMimeType = mime_content_type($this->demande->requestImg);

            if ($realMimeType === 'image/vnd.microsoft.icon') {
                ConvertIco::convert($this->demande, $this->conf->icoSize);
            }

            if ($realMimeType === 'image/svg+xml') {
                ConvertIco::convert($this->demande, $this->conf->icoSize);
            }

            $image = new Zebra_Image();
            $image->source_path = $this->demande->requestImg;
            $image->target_path = $this->demande->requestImg;
            $image->preserve_time = false;
            $image->enlarge_smaller_images = false;
            $image->resize($this->conf->icoSize, $this->conf->icoSize, ZEBRA_IMAGE_CROP_TOPLEFT);
        } catch (\Exception $e) {
            $this->db->addUpdate(2);
            copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
            return true;
        }

        if (!is_file($this->demande->requestImg)) {
            copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
            $this->db->addUpdate(2);
            return true;
        } else {
            $this->db->addUpdate(1);
        }
    }

    public function show() {
        if (!file_exists($this->requestImg) && $this->type === 'fav') {
            $this->makeFavicon();
        }

        //n_print($this);

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