<?php

namespace App\EventListener;

use Pimcore\Event\AssetEvents;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Model\Metadata\Predefined;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Throwable;

class AssetListener implements EventSubscriberInterface
{
	public static function getSubscribedEvents()
	{
		return [
			AssetEvents::POST_ADD => 'onAssetPostAdd'
		];
	}

	public function onAssetPostAdd(AssetEvent $event)
	{
		$asset = $event->getAsset();
        if(!$asset) return;

		// add predefined metadata to created asset
		$metadataList = new Predefined\Listing();
		$metadataList->load();
		$definitions = $metadataList->getDefinitions();

		$predefinedMetadata = array_map(fn($definition) => [
			'name' => $definition->getName(),
			'type' => $definition->getType(),
			'data' => $definition->getData() ?: '',
			'language' => $definition->getLanguage(),
		], $definitions);

		$asset->setMetadataRaw($predefinedMetadata);

		try {
			$asset->save();
		} catch (Throwable $throwable) {

		}
	}
}
