<?php

namespace onespace\tools\widgets\loaders;

use yii\helpers\Html;

final class TextLoader extends \yii\base\Widget {

    /**
     * The text content of the loader.
     * 
     * @var string  $text   The loading text.
     * 
     * @access  public
     */

    public string $text = 'Loading...';

    /**
     * An animated spinner to append to the beginning of the text.
     * 
     * @var   string|null $spinner    Default: null
     * 
     * @access  public
     */

    public ?string $spinner = null;

    /**
     * Whether or not to pulse animate the loader.
     * 
     * @var bool    $animate    Default: false
     * 
     * @access  public
     */

    public bool $animate = false;

    /**
     * Added a custom tag option.
     * 
     * @var string  $tag    Default: 'p'
     * 
     * @access  public
     */

    public string $tag = 'p';

    /**
     * The params for the `<p>` tag.
     * 
     * @var array   $params Default: []
     * 
     * @access  private
     */

    private array $params = [];


    /**
     * {@inheritdoc}
     */

    public function init() {
        if ($this->animate) {
            $view = $this->getView();
            $view->registerCss(<<<CSS
            @keyframes textLoadingPulse {
                0% {
                    transform: scale(1);
                }
                50% {
                    transform: scale(1.1);
                }
                100% {
                    transform: scale(1);
                }
            }

            .pulse-loading {
                animation: textLoadingPulse 1s infinite alternate;
                display: inline-block;
            }
            CSS);
            $this->params['class'] = 'pulse-loading';
        }

        if (!is_null($this->spinner)) {
            $this->text = implode(' ', [$this->spinner, $this->text]);
            $this->tag = 'div';
        }
    }


    /**
     * {@inheritdoc}
     */

    public function run(): string {
        return Html::tag($this->tag, $this->text, $this->params);
    }
}
