<?php

namespace onespace\tools\widgets\ui\views\datacard;

use Exception;
use onespace\tools\widgets\ui\views\datacard\DataCard;
use Yii;
use yii\base\Widget;
use yii\widgets\Pjax;

/**
 * Widget for laying out the Data Card interface.
 * 
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

final class DataCardsView extends Widget {

    /**
     * The cards to draw into the view.
     * 
     * Each item of the array should either be an
     * array of instances of the `onespace\tools\widgets\ui\views\datacard\DataCard` widget, or an array with
     * the following possible keys:
     * 
     * ```php
     * [
     * 'link' => ...
     * 'image' => ...
     * 'heading' => ...
     * 'details' => ...
     * 'edit' => ...
     * 'delete' => ...
     * 'selected' => ...
     * ];
     * ```
     * 
     * @see src/ui/DataCard.php
     * 
     * @var array   $data
     * 
     * @access  public
     */

    public array $data;

    /**
     * Whether or not to use PJAX automatically. Set to false to set your own PJAX options.
     * 
     * @var bool    $use_pjax   Default: true
     * 
     * @access  public
     */

    public bool $use_pjax = true;


    /**
     * {@inheritdoc}
     */

    public function init() {
        parent::init();
        if (!isset($this->data)) {
            throw new Exception("Data not set");
        }
    }


    /**
     * {@inheritdoc}
     * 
     * @return  string
     */

    public function run(): string {
        parent::run();
        if ($this->use_pjax) {
            $pjax_id = 'pj' . Yii::$app->security->generateRandomString(8);
            Pjax::begin([
                'id' => $pjax_id,
                'linkSelector' => "#{$pjax_id} .ui-data-cards-view .ui-card-container a",
            ]);
        }

        $card = '';
        $card .= "<div class='ui-data-cards-view'>";
        foreach ($this->data as $entry) {
            if ($entry instanceof DataCard) {
                $card .= $entry;
            } else {
                $card .= DataCard::widget([
                    'link'     => $entry['link']    ?? null,
                    'image'    => $entry['image']   ?? null,
                    'heading'  => $entry['heading'] ?? '',
                    'details'  => $entry['details'] ?? '',
                    'edit'     => $entry['edit']    ?? false,
                    'delete'   => $entry['delete']  ?? false,
                    'selected' => $entry['selected']  ?? false,
                ]);
            }
        }
        $card .= '</div>'; // ui-data-cards-view

        if ($this->use_pjax) {
            Pjax::end();
        }
        return $card;
    }
}
