<?php

namespace onespace\tools\activeApi\components\dataProviders;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * Provides a dataProvider for an array of prefilled `ActiveApiModels`.
 */
class ActiveApiDataProvider extends \yii\data\BaseDataProvider {
    /**
     * @var \common\models\api\base\BaseActiveApiModel[] $models
     */
    public array $models = [];

    /**
     * {@inheritdoc}
     */
    protected function prepareModels() {
        $this->setModels($this->models);

        if (count($this->models) > 0) {
            $model = array_values($this->models)[0];

            if ($this->sort !== false && empty($this->sort->attributes)) {
                foreach ($model->attributes() as $attribute) {
                    $this->sort->attributes[$attribute] = [
                        'asc' => [$attribute => SORT_ASC],
                        'desc' => [$attribute => SORT_DESC],
                    ];
                }
            }

            if ($this->pagination !== false) {
                try {
                    $this->pagination->totalCount = $model->getTotalSearchResults();
                } catch (\Throwable $th) {
                    // Stick to defaults
                    Yii::debug("Using default Total", __METHOD__);
                }

                try {
                    $this->pagination->setPage($model->getOffsetResults());
                } catch (\Throwable $th) {
                    // Stick to defaults
                    Yii::debug("Using default page", __METHOD__);
                }

                try {
                    $pageSize = $model->getLimitResults();
                    if ($pageSize) {
                        $this->pagination->setPageSize($model->getLimitResults());
                    }
                } catch (\Throwable $th) {
                    // Stick to defaults
                    Yii::debug("Using default page size", __METHOD__);
                }
            }
        }
        return $this->getModels();
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareKeys($models) {
        $keys = [];
        foreach ($models as $model) {
            $keys[] = ArrayHelper::getValue($model, 'id');
        }
        return $keys;
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareTotalCount() {
        if (count($this->models) > 0) {
            try {
                $model = array_values($this->models)[0];
                return $model->getTotalSearchResults();
            } catch (\Throwable $th) {
                return count($this->models);
            }
        }
        return 0;
    }
}
