<?php
class AVUP_Native_Item {
	protected $item,
				$video_block,
				$params;

	function __construct( $video_block ) {
		$this->video_block = $video_block;
	}

	public function init( $params, $feed_infos ) {

		if ( empty( $params ) || empty( $feed_infos ) ) {
			return false;
		}

		$params     = json_decode( json_encode( $params ), true );
		$feed_infos = json_decode( json_encode( $feed_infos ), true );
		$partner_id = $params['partner']['id'];

		$this->params = $params;

		$this->item['id']              = $params['video_id'];
		$this->item['title']           = $this->get_partner_feed_infos( 'feed_item_title', $partner_id, $feed_infos );
		$this->item['desc']            = $this->get_partner_feed_infos( 'feed_item_desc', $partner_id, $feed_infos );
		$this->item['tags']            = $this->get_partner_feed_infos( 'feed_item_tags', $partner_id, $feed_infos );
		$this->item['duration']        = $this->get_partner_feed_infos( 'feed_item_length', $partner_id, $feed_infos );
		$this->item['duration_format'] = $this->get_partner_feed_infos( 'feed_item_length_format', $partner_id, $feed_infos );
		$this->item['thumb_url']       = $this->get_partner_feed_infos( 'feed_item_thumb_url', $partner_id, $feed_infos );
		$this->item['thumbs_urls']     = $this->get_partner_feed_infos( 'feed_item_thumbs_urls', $partner_id, $feed_infos );
		$this->item['trailer_url']     = $this->get_partner_feed_infos( 'feed_item_trailer_url', $partner_id, $feed_infos );
		$this->item['video_url']       = $this->get_partner_feed_infos( 'feed_item_video_url', $partner_id, $feed_infos );
		$this->item['tracking_url']    = $this->get_partner_feed_infos( 'feed_item_join_url', $partner_id, $feed_infos );
		$this->item['code']            = $this->get_partner_feed_infos( 'feed_item_code', $partner_id, $feed_infos );
		$this->item['actors']          = $this->get_partner_feed_infos( 'feed_item_actors', $partner_id, $feed_infos );
	}

	public function get_id() {
		return AVUP_Item::get_id( $this->item );
	}

	public function is_valid() {
		return AVUP_Item::is_valid( $this->item );
	}

	public function get_data_for_js() {
		return AVUP_Item::get_data_for_js( $this->item );
	}

	public function get_data_for_json() {
		return AVUP_Item::get_data_for_json( $this->item );
	}

	private function get_partner_feed_infos( $partner_feed_item, $partner_id, $feed_infos ) {
		$output         = false;
		$feed_item_type = isset( $feed_infos[ $partner_feed_item ] ) ? key( $feed_infos[ $partner_feed_item ] ) : null;
		$short_item     = '';
		if ( isset( $feed_infos[ $partner_feed_item ][ $feed_item_type ] ) ) {

			$short_item = $feed_infos[ $partner_feed_item ][ $feed_item_type ];

			if ( $feed_item_type != 'find' ) {

				$results = array();
				preg_match_all( '/<%(.+)%>/U', $short_item, $results );
				foreach ( $results[1] as $result ) {
					if ( strpos( $result, 'get_partner_option' ) !== false ) {
						$saved_partner_options = WPSCORE()->get_product_option( 'AVUP', $partner_id . '_options' );
						$option                = str_replace( array( 'get_partner_option("', '")' ), array( '', '' ), $result );
						$new_result            = '$saved_partner_options["' . $option . '"]';
						$short_item            = str_replace( '<%' . $result . '%>', eval( 'return ' . $new_result . ';' ), $short_item );
					} else {
						$short_item = str_replace( '<%' . $result . '%>', eval( 'return ' . $result . ';' ), $short_item );
					}
				}
				unset( $results );
			}

			switch ( $feed_item_type ) {
				case 'find':
					$video_block = $this->video_block;
					$query       = $short_item['query'];
					$offset      = $short_item['offset'];
					$attr        = $short_item['attr'];

					if ( isset( $short_item['loop'] ) && isset( $short_item['separator'] ) ) {

						$blocks = $video_block->find( (string) $query );

						foreach ( (array) $blocks as $block ) {
							$output[] = $block->{$attr};
						}

						$output = implode( $short_item['separator'], (array) $output );

					} else {
						if ( $query != '' ) {
							$dom_item = $video_block->find( (string) $query, (int) $offset );
							if ( null === $dom_item ) {
								$output = '';
							} else {
								$output = $dom_item->{$attr};
								if ( isset( $short_item['regex'] ) ) {
									$exploded_regex  = explode( '/', $short_item['regex'] );
									$regex_modifiers = end( $exploded_regex );

									preg_match_all( $short_item['regex'], $output, $results );

									if ( false !== strpos( $regex_modifiers, 'U' ) ) {
										// prevent duplicates in results.
										$unique_results = array_unique( $results[1] );
										// transform array to string.
										$output = implode( ',', $unique_results );
										// avoid " chars.
										$output = str_replace( '"', '', $output );
									} else {
										if ( $results[1][0] ) {
											$output = $results[1][0];
										} else {
											$output = '';
										}
									}
								}
							}
						} else {
							$output = $video_block->{$attr};
						}
					}
					break;

				default:
					$output = $short_item;
					break;
			}

			// xhamster thumbs
			if ( 'xhamster' == $partner_id ) {

				// thumb rotation has been removed from xhamster
				// if( 'feed_item_thumbs_urls' == $partner_feed_item ){
				// if( strpos($output, 'thumb-v-ec2') === false ){
				// case : https://thumb-v-ec.xhcdn.com/t/200/640/4_736200.jpg
				// $regex              = '/^(.+)[0-9]+_([0-9]+).jpg$/';
				// $thumb_url          = $output;
				// preg_match($regex, $thumb_url, $matches, PREG_OFFSET_CAPTURE, 0);
				// $thumbs_base_url    = $matches[1][0];
				// $video_id           = $matches[2][0];
				// $thumbs             = array();
				// for($i = 1; $i <= 10; $i++){
				// $thumbs[] = $thumbs_base_url . $i . '_' . $video_id . '.jpg';
				// }
				// $output = implode(',', $thumbs);
				// }else{
				// case : https://thumb-v-ec2.xhcdn.com/a/153M-oMe3jLtB1Mc21Ypgg/009/239/888/640x360.6.jpg
				// no thumbnails
				// $output = '';
				// }
				// }
			}
		}
		if ( ! $output ) {
			return false;
		}
		return AVUP_Item::clean_string( $output );
	}
}
