<?php

namespace onespace\tools\widgets\chartjs;

use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use yii\web\View;

/**
 * Impliment a Yii2 widget to draw a ChartsJS chart.
 * 
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

final class ChartJs extends Widget {

    /**
     * The ID of the chart `<canvas>` element. If not specified, a random
     * string will be generated.
     * 
     * @var string  $id
     * 
     * @access  public
     */

    public string $id;

    /**
     * When the JavaScript chart element should be loaded from the page.
     * 
     * ## Options
     * 
     * - `\yii\web\View::POS_HEAD`
     * - `\yii\web\View::POS_BEGIN`
     * - `\yii\web\View::POS_END`
     * - `\yii\web\View::POS_READY`
     * - `\yii\web\View::POS_LOAD`
     * 
     * @var int $jsLoad Default: `View::POS_READY`
     * 
     * @access  public
     */

    public int $jsLoad = View::POS_READY;

    /**
     * The chart data to be passed to the chart. Pass as an array for convenience.
     * Pass as a string if you need to use any JS methods such as `array.map` in
     * the data.
     * 
     * @var array|string    $data   Default: []
     * 
     * @access  public
     */

    public array|string $data = [];


    /**
     * {@inheritdoc}
     */

    public function init() {
        $view = $this->getView();
        \onespace\tools\assets\ChartJSAsset::register($view);

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

        if (is_array($this->data)) {
            $this->data = json_encode($this->data);
        }

        $view->registerJs(<<<JS
        new Chart(document.querySelector('#{$this->id}'), $this->data);
        JS, $this->jsLoad);
    }


    /**
     * {@inheritdoc}
     */

    public function run() {
        echo Html::tag('canvas', options: ['id' => $this->id]);
    }
}
