<?php
/**
 * Created by Error202
 * Date: 03.10.2017
 */

namespace core\widgets;

use yii\base\Widget;
use yii\helpers\Url;
use Yii;

class FaviconWidget extends Widget
{
    public $iconsPath;
    public $iconsUrl;

    public function run()
    {
        /** @var \yii\web\View $View */
        $View = \Yii::$app->get('view');

        $this->iconsPath = Yii::getAlias('@staticRoot') . '/cache/favicon';
        $this->iconsUrl = Yii::getAlias('@static') . '/cache/favicon';

        foreach ([16, 32, 96, 194] as $s) {
            $filename = sprintf('favicon-%sx%s.png', $s, $s);
            $filepath = $this->iconsPath . '/' . $filename;
            if (!empty($filepath) && file_exists($filepath)) {
                $View->registerLinkTag([
                    'rel' => 'icon',
                    'type' => 'image/png',
                    'href' => Url::to(sprintf('%s/%s', $this->iconsUrl, $filename)),
                    'sizes' => sprintf('%sx%s', $s, $s),
                ], basename($filepath));
            }
        }

        $filepath = $this->iconsPath . '/' . 'android-chrome-192x192.png';
        if (!empty($filepath) && file_exists($filepath)) {
            $View->registerLinkTag([
                'rel' => 'icon',
                'type' => 'image/png',
                'href' => Url::to(sprintf('%s/android-chrome-192x192.png', $this->iconsUrl)),
                'sizes' => sprintf('%sx%s', 192, 192),
            ], basename($filepath));
        }

        foreach ([57, 60, 72, 76, 114, 120, 144, 152, 180] as $s) {
            $filename = sprintf('apple-touch-icon-%sx%s.png', $s, $s);
            $filepath = $this->iconsPath . '/' . $filename;
            if (!empty($filepath) && file_exists($filepath)) {
                $View->registerLinkTag([
                    'rel' => 'apple-touch-icon',
                    'type' => 'image/png',
                    'href' => Url::to(sprintf('%s/%s', $this->iconsUrl, $filename)),
                    'sizes' => sprintf('%sx%s', $s, $s),
                ], basename($filepath));
            }
        }
        $filepath = $this->iconsPath . 'mstile-144x144.png';
        if (!empty($filepath) && file_exists($filepath)) {
            $View->registerMetaTag([
                'name' => 'msapplication-TileImage',
                'content' => Url::to(sprintf('%s/mstile-144x144.png', $this->iconsUrl)),
            ], basename($filepath));
        }

        $filepath = Yii::getAlias('@webroot') . '/' . 'manifest.json';
        if (!empty($filepath) && file_exists($filepath)) {
            $View->registerLinkTag([
                'rel' => 'manifest',
                'href' => Url::to(sprintf('%s/manifest.json', Yii::getAlias('@web'))),
            ], basename($filepath));
        }
    }
}