<?php

namespace Src\Modules\JsonObjects\Infrastructure;

use Src\Modules\JsonObjects\Interfaces\Infrastructure\IDirsStorage;
use Src\Modules\JsonObjects\Interfaces\Infrastructure\IDirsQuery;
use Src\Common\Infrastructure\TraitStorage;

class DirsStorage implements IDirsStorage
{

    use TraitStorage;

    protected IDirsQuery $query;

    protected IDirsQuery $parentQuery;

    public function setQuery(IDirsQuery $query)
    {
        $this->query = $query;
    }

    public function setParentQuery(IDirsQuery $query)
    {
        $this->parentQuery = $query;
    }

    public function getById($id, array $dsl = []): array
    {
        $this->query->select($dsl)->whereId($id);
        $data = $this->query->one();
        if (!$data) {
            return [];
        }
        if (key_exists('parent', $dsl)) {
            $parentData = $this->parentQuery->select($dsl['parent'])->whereId($data['parent_id'])->all();
            $data['parent'] = $parentData;
        }
        if (key_exists('path', $dsl) && isset($data['matherial_path'])) {
            $ids = explode('|', $data['matherial_path']);
            $path = $this->query->select($dsl['path'])->whereIdIn($ids)->all();
            $data['path'] = $path;
        }
        return $data;
    }

    public function getByParentId($parentId, array $dsl = []): array
    {
        return $this->query->select($dsl)->whereParentId($parentId)->all();
    }

    public function getIdsInDir(string $dirId): array
    {
        $dirData = $this->query->select(['id', 'matherial_path'])->whereId($dirId)->one();
        $pathIds = ($dirData['matherial_path']) ? explode('|', $dirData['matherial_path']) : [];
        $pathIds[] = $dirId;
        $matherialPath = join('|', $pathIds);
        $dirs = $this->query->select(['id'])->whereInPath($matherialPath)->all();
        $ids = array_map(function ($dir) {
            return $dir['id'];
        }, $dirs);
        return array_values($ids);
    }
}
