<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Dynamic\Listener;

use YOOtheme\Arr;
use YOOtheme\Builder\Source;
use ZOOlanders\YOOessentials\Dynamic\DynamicResolver;

class ExpandCoreSources
{
    /**
     * @param Source $source
     */
    public function handle($source)
    {
        $definitions = DynamicResolver::getSourceTypeDefinitions($source);
        $queryFields = $definitions['Query']->config['fields'] ?? [];

        foreach (Arr::omit($definitions, ['Object', 'Query']) as $type) {
            $fields = (array) ($type->config['fields'] ?? []);

            foreach ($fields as $name => $field) {
                $filters = $field['metadata']['filters'] ?? [];

                if (in_array('date', $filters) && !in_array('datemodify', $filters)) {
                    $type->config['fields'][$name]['metadata']['filters'] = array_merge($filters, ['datemodify']);
                }
            }
        }

        if (isset($queryFields['file']) && isset($queryFields['files'])) {
            $source->queryType([
                'fields' => [
                    'file' => [
                        'metadata' => [
                            'fields' => [
                                'pattern' => [
                                    'source' => 'true',
                                ],
                                'offset' => [
                                    'source' => 'true',
                                ],
                            ]
                        ]
                    ],
                    'files' => [
                        'metadata' => [
                            'fields' => [
                                'pattern' => [
                                    'source' => 'true',
                                ],
                                '_offset' => [
                                    'fields' => [
                                        'offset' => [
                                            'source' => 'true',
                                        ],
                                        'limit' => [
                                            'source' => 'true',
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ],
                ],
            ]);
        }
    }
}
