<?php

namespace WordPress\DataLiberation\DataFormatConsumer;

use WordPress\DataLiberation\DataLiberationException;

/**
 * Represents the result of a {data format} -> block markup conversion.
 */
class BlocksWithMetadata {

	private $block_markup;
	private $metadata;

	public function __construct( $block_markup, $metadata = array() ) {
		$this->block_markup = $block_markup;
		$this->metadata     = $metadata;
		foreach ( $this->metadata as $key => $values ) {
			if ( ! is_array( $values ) ) {
				throw new DataLiberationException( sprintf( 'Metadata values for the key %s must be an array but was %s', esc_html( $key ), esc_html( gettype( $values ) ) ) );
			}
		}
	}

	/**
	 * Gets the first metadata value for a given key.
	 *
	 * Example:
	 *
	 * Metadata:
	 * array(
	 *     'post_title' => array( 'The Name of the Wind' ),
	 *     'post_author' => array( 'Patrick Rothfuss', 'Betsy Wollheim' )
	 * )
	 *
	 * get_first_meta_value( 'post_author' ) returns 'Patrick Rothfuss'.
	 *
	 * @param  string $key  The metadata key.
	 *
	 * @return mixed The metadata value.
	 */
	public function get_first_meta_value( $key ) {
		if ( ! array_key_exists( $key, $this->metadata ) ) {
			return null;
		}

		return $this->metadata[ $key ][0];
	}

	/**
	 * Gets all the metadata sourced from the input document by the convert() method.
	 * The data format is:
	 *
	 * Array(
	 *     'post_title' => array( 'The Name of the Wind' ),
	 *     'post_author' => array( 'Patrick Rothfuss', 'Betsy Wollheim' )
	 * )
	 *
	 * Note each meta key may have multiple values. The consumer of this interface
	 * must account for this.
	 *
	 * @param array $options Optional parameters.
	 * @return array The metadata sourced from the input document.
	 */
	public function get_all_metadata( array $options = array() ) {
		if ( isset( $options['first_value_only'] ) && $options['first_value_only'] ) {
			$meta = array();
			foreach ( $this->metadata as $key => $values ) {
				$meta[ $key ] = $values[0];
			}

			return $meta;
		}

		return $this->metadata;
	}

	/**
	 * Gets the block markup generated by the convert() method.
	 *
	 * @return string The block markup.
	 */
	public function get_block_markup() {
		return $this->block_markup;
	}
}
