<?php

namespace App\Traits;

use Illuminate\Support\Facades\App;
use Mtc\ContentManager\Contracts\ContentElementField;
use Mtc\ContentManager\Contracts\FormField;
use Mtc\ContentManager\Contracts\TemplateElement;

trait RetrievesFieldData
{
    protected function getContentElementFieldData(ContentElementField $field)
    {
        $data = array_merge($field->data ?? [], $field->meta ?? []);
        $data['fieldId'] = $field->field_type;

        if (!isset($data['icon'])) {
            $data['icon'] = $this->getFieldIcon($field);
        }
        if (!isset($data['component'])) {
            $data = array_merge($data, $this->fieldComponentNames($this->getField($field->field_type)));
        }
        return $data;
    }

    /**
     * The registered Vue component name (prefixed) plus the bare name used to build option-dialog
     * import paths. Single source of truth for content and property field resources.
     */
    protected function fieldComponentNames(?FormField $field): array
    {
        $component = $field?->getComponent();

        return [
            'component' => 'EditableContent' . $component,
            'componentName' => $component,
        ];
    }

    private function getFieldIcon(ContentElementField|TemplateElement $field): ?string
    {
        if ($field->field_type === 'element') {
            if ($field instanceof ContentElementField && !empty($field->childElement?->icon)) {
                return $field->childElement?->icon ?? 'layer-group';
            }
            if ($field instanceof TemplateElement && !empty($field->element?->icon)) {
                return $field->element?->icon ?? 'layer-group';
            }
        }
        return $this->getField($field->field_type)?->getIcon();
    }

    private function getField(?string $field_type): ?FormField
    {
        if ($field_type === null || $field_type === 'element') {
            return null;
        }
        try {
            return App::make(config("pages.field_types.$field_type"));
        } catch (\Exception) {
            return null;
        }
    }
}
