<?php

namespace onespace\tools\activeApi\models;

use onespace\tools\activeApi\helpers\ApiClientHelperTrait;
use onespace\tools\activeApi\helpers\CreateUpdateDeleteHelperTrait;
use onespace\tools\activeApi\helpers\QueryHelperTrait;
use yii\helpers\ArrayHelper;

/**
 * The base API model class used by active API models.
 *
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */
abstract class BaseActiveApiModel extends \yii\base\Model {
    use ApiClientHelperTrait;
    use QueryHelperTrait;
    use CreateUpdateDeleteHelperTrait;

    /**
     * Sets the default page size. Overwrite in model if a different
     * value is desired.
     *
     * @var int DEFAULT_PAGE_SIZE   Default: 20
     *
     * @access  public
     */

    public const DEFAULT_PAGE_SIZE = 20;

    /**
     * Prepares the limit, offset and sort value, to send to the API
     * request. Handles default values if not set.
     *
     * Overwrite in model if a different method is desired.
     *
     * @param   array   $params An associative array possible values. Usually set from `$_GET`.
     *
     * @return  array   `[$limit, $offset, $sort]`
     *
     * @access  protected
     */
    protected function setLimitOffsetSort(array $params): array {
        $limit = ArrayHelper::getValue($params, 'per-page', static::DEFAULT_PAGE_SIZE);
        $offset = (ArrayHelper::getValue($params, 'page', 0) - 1);
        $offset = $offset < 0 ? 0 : $offset;
        $sort = ArrayHelper::getValue($params, 'sort', null);

        return [$limit, $offset, $sort];
    }

    /**
     * {@inheritdoc}
     */
    public function afterFind(): void {
    }

    /**
     * {@inheritdoc}
     */
    public function beforeSave(bool $insert): bool {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function afterSave(): void {
    }

    /**
     * Loosely loads values into model.
     * Prevents property not found exceptions.
     */
    public function __construct($config = []) {
        foreach ($config as $key => $_) {
            if (!property_exists($this, $key)) {
                unset($config[$key]);
            }
        }

        parent::__construct($config);
    }
}
