<?php

namespace App\Transformers\Objects;

use App\Models\Objects\Field;
use App\Services\Filters\FiltersService;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Primitive;
use League\Fractal\TransformerAbstract;

class FieldTransformer extends TransformerAbstract {
    protected array $filters;
    protected ?FiltersService $service;

    public function __construct($filters = [], ?FiltersService $service = null) {
        $this->filters = $filters;
        $this->service = $service;
    }

    protected array $defaultIncludes = [

    ];

    protected array $availableIncludes = [
        'value', 'options', 'range', 'represented'
    ];

    public function transform(Field $model): array {
        return [
            'id' => $model->uuid,
            'type' => $model->type,
            'name' => $model->name,
            'title' => $model->title,
            'required' => boolval($model->required),
            'multiple' => boolval($model->multiple),
            'filterable' => boolval($model->filterable),
            'hidden' => boolval($model->hidden),
            'related' => $model->params['related'] ?? null,
            'appearance' => $model->params['appearance'] ?? null
        ];
    }

    public function includeValue(Field $model) {
        if ($value = $this->filters[$model->name] ?? null) {
            if ($class = $model->params['related'] ?? null) {
                $value = $class::query()->whereIn('uuid', is_array($value) ? $value : [$value])->get();
                return $this->collection($value, $model->transformer);
            } else return $this->primitive($value);
        }
    }

    public function includeOptions(Field $model): ?Collection {
        return $model->options ? $this->collection($model->options, $model->transformer) : null;
    }

    public function includeRange(Field $model): ?Primitive {
        return ($res = $model->getRange($this->filters, $this->service)) ? $this->primitive($res) : null;
    }

    public function includeRepresented(Field $model): ?Collection {
        return ($res = $model->getRepresented($this->filters, $this->service)) ? $this->collection($res, $model->transformer) : null;
    }


}
