<?php

namespace onespace\tools\widgets\loaders;

use onespace\tools\widgets\helpers\AsyncBlockJS;
use Yii;
use yii\base\Widget;
use yii\helpers\Html;

final class BounceLoader extends Widget {

    public string $id;
    public bool $asyncLoad = false;

    private string $logo;
    private string $altAppName;


    /**
     * {@inheritdoc}
     */

    public function init(): void {
        parent::init();

        if ($this->asyncLoad) {
            AsyncBlockJS::widget();
        }

        $this->id ??= str_replace('-', '_', Yii::$app->security->generateRandomString(8));

        $app = Yii::$app->request->cookies->getValue('_app', 'Default');
        if ($app == 'Cloudsecure') {
            $logo = 'CloudSecureIcon.png';
            $this->altAppName = $app;
        } else {
            $name = Yii::$app->name;
            $altAppMap = ['gatebook 2.0' => 'Gatebook', 'gatebook 1.0' => 'Gatebook', 'onespace' => 'OneSpace'];
            $logo = 'onespaceIcon-Inverse.svg';
            $this->altAppName = $altAppMap[strtolower($name)] ?? '';
        }

        
        if (class_exists(\common\assets\ImageAsset::class)) {
            $this->logo = \common\assets\ImageAsset::getImageUrl($logo);
            } else {
            $this->logo ??= 'onespaceLogo.svg';
            $this->logo = "@web/img/{$this->logo}";
        }
    }


    /**
     * {@inheritdoc}
     */

    public function run(): string {
        parent::run();
        $img = Html::img($this->logo, ['alt' => $this->altAppName, 'height' => '55%', 'style' => 'margin-left: -6%;']);
        return <<<HTML
        <div class='loading-block' id="{$this->id}">
            <div class="pace pace-active">
                <div class="pace-progress" data-progress="50" data-progress-text="50%"
                    style="-webkit-transform: translate3d(50%, 0px, 0px); -ms-transform: translate3d(50%, 0px, 0px); transform: translate3d(50%, 0px, 0px);">
                    <div class="pace-progress-inner"></div>
                </div>
                <div class="pace-activity">
                    $img
                </div>
            </div>
        </div>
        HTML;
    }


    /**
     * Return if a PJAX call has been made
     * 
     * @return  bool
     * 
     * @static
     * @access  public
     */

    public static function getPjaxCall(): bool {
        return \Yii::$app->request->isAjax && strpos(\Yii::$app->request->get("_pjax"), 'pjax-main') !== false;
    }
}
