<?php

namespace Src\Modules\JsonObjects\Infrastructure;

use Src\Modules\JsonObjects\Interfaces\Infrastructure\IItemStorage;
use Src\Modules\JsonObjects\Interfaces\Infrastructure\IItemQuery;
use Src\Modules\JsonObjects\Interfaces\Infrastructure\IDirsStorage;
use Src\Common\Infrastructure\TraitStorage;

class ItemStorage implements IItemStorage
{

    use TraitStorage;

    protected IItemQuery $objectsQuery;

    protected IDirsStorage $dirsStorage;

    public function setObjectsQuery(IItemQuery $query)
    {
        $this->objectsQuery = $query;
    }

    public function setDirStorage(IDirsStorage $storage): void
    {
        $this->dirsStorage = $storage;
    }

    public function getById(string $itemId, array $dsl = []): array
    {
        $itemData = $this->objectsQuery->select($dsl)->whereId($itemId)->one();
        if (empty($itemData)) {
            return [];
        }
        if (key_exists('dir', $dsl)) {
            $dirId = $itemData['dir_id'];
            $dirData = $this->dirsStorage->getById($dirId, $dsl['dir']);
            $itemData['dir'] = [
                $dirId => $dirData,
            ];
        }
        return $itemData;
    }

    public function getByIds(array $ids, array $dsl = []): array
    {
        $itemsData = $this->objectsQuery->select($dsl)->whereIdIn($ids)->all();
        return $itemsData;
    }

    public function getByType(string $type, int $limit, int $offset, array $dsl = []): array
    {
        $itemsData = $this->objectsQuery->select($dsl)->limit($limit, $offset)->whereType($type)->all();
        return $itemsData;
    }

    public function getByKey(string $key, array $dsl = []): array
    {
        return $this->objectsQuery->select($dsl)->whereKey($key)->one();
    }

    public function getByDirId(string $dirId, array $dsl = []): array
    {
        return $this->objectsQuery->select($dsl)->whereDirId($dirId)->all();
    }
}
