<?php

namespace Depicter\Document\Models\Elements;

use Averta\Core\Utility\Arr;
use Averta\Core\Utility\JSON;
use Depicter\Document\Models\Common\Styles;
use Depicter\Document\Models\Element;
use Depicter\Html\Html;

class Component extends Element
{

	/**
	 * Render arrow markup
	 *
	 * @return \TypeRocket\Html\Html|void
	 * @throws \JsonMapper_Exception
	 */
	public function render() {
		$args = $this->getDefaultAttributes();
		return Html::div( $args );
	}

	public function getDefaultAttributes(){
		$parentAttrs = parent::getDefaultAttributes(); // TODO: Change the autogenerated stub

		$options = $this->options;
		foreach( $options as $key => $option ) {
			if ( strpos( $key, 'imageAsset' ) ) {
				if ( is_object( $options->$key ) ) {
					$source = $this->hasDataSheet() ? $this->maybeReplaceDataSheetTags( $options->$key->src ) : $options->$key->src;
					$options->$key->srcset = \Depicter::media()->getSrcSet( $source );
					$options->$key->src = \Depicter::media()->getSourceUrl( $source );
				} else {
					// $option is string and is the src id of image asset
					$source = $this->hasDataSheet() ? $this->maybeReplaceDataSheetTags( $option ) : $option;
					$options->$key = \Depicter::media()->getSourceUrl( $source );
				}
			} else if ( $key == 'choices' ) {
				foreach( $option as $optionKey => $choice ) {
					foreach ( $choice as $choiceKey => $value ) {
						if ( strpos( $choiceKey, 'imageAsset' ) ) {
							$source = $this->hasDataSheet() ? $this->maybeReplaceDataSheetTags( $value ) : $value;
							$options->$key[ $optionKey ]->$choiceKey = [
								'src' => \Depicter::media()->getSourceUrl( $source ),
								'srcset' => \Depicter::media()->getSrcSet( $source )
							];
						}
					}
				}
			}
		}

		$componentProps = JSON::encode( $options );
		$componentProps = str_replace( ':imageAsset', '', $componentProps );

		$attrs = [
			'data-component-type' => $this->componentType,
			'data-component-props' => $componentProps
		];

		return Arr::merge( $attrs, $parentAttrs );
	}
}
