<?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['component'] = 'EditableContent' . $this->getField($field->field_type)?->getComponent();
            $data['componentName'] = $this->getField($field->field_type)?->getComponent();
        }
        return $data;
    }

    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 $exception) {
            return null;
        }
    }
}
