<?php
/**
 * @package    YouTubeR
 * @license  https://allforjoomla.ru/license
 *
 * Created by Oleg Micriucov for Joomla! 3.x
 * https://allforjoomla.ru
 *
 */
defined( '_JEXEC' ) or die;
require_once(dirname(__FILE__).'/base.php');

class mxYouTuberView_playlist extends mxYouTuberView_base{
	
	public function __construct($attribs,$controller){
		parent::__construct($attribs,$controller);

		$this->setTemplate('playlist');
		$dataModel = $this->getDataModel();
		$this->playlist = new stdclass;
		$ids = array();
		if(isset($attribs['videos'])&&trim($attribs['videos'])!=''){
			$tmp = explode(',',$attribs['videos']);
			foreach($tmp as $tm){
				$id = trim($tm);
				if($id!=''){
					$ids[] = $id;
				}
			}
		}
		else if($attribs['id']){
			$this->playlist = $dataModel->getPlaylistItems( $attribs['id'], $attribs['limit'], $attribs['pageToken']);
			foreach($this->playlist->items as $item){
				$ids[] = $item->snippet->resourceId->videoId;
			}
			
			if(isset($attribs['except_videos'])&&trim($attribs['except_videos'])!=''){
				$exIDs = explode(',',preg_replace('~\s~','',$attribs['except_videos']));
				$diff = array_intersect($ids,$exIDs);
				if(count($diff)){
					$ids = array();
					$this->playlist = $dataModel->getPlaylistItems( $attribs['id'], $attribs['limit']+count($diff), $attribs['pageToken']);
					foreach($this->playlist->items as $item){
						$ids[] = $item->snippet->resourceId->videoId;
					}
				}
				$filteredIDs = array();
				foreach($ids as $id){
					if(!in_array($id,$exIDs)){
						$filteredIDs[] = $id;
					}
				}
				$ids = $filteredIDs;
				unset($filteredIDs);
			}
		}
		else{
			throw new Exception(JText::_('PLG_SYSTEM_YOUTUBER_NO_PLAYLIST_AND_VIDEO_ID'));
		}
		
        $this->videos = $dataModel->getVideo($ids);
		$this->orderVideos($this->videos,$attribs['order_by'],$attribs['order_dir']);
		
		$attribs['rel'] = 'mxYouTubeR'.md5($attribs['id'].$attribs['theme']);

		if($attribs['size']==''){
			$attribs['size'] = 'medium';
		}

		$this->showTitle = strpos($attribs['display'],'title')!==false;
		$this->showDate = strpos($attribs['display'],'date')!==false;
		$this->showDescription = strpos($attribs['display'],'description')!==false;
		$this->showMeta = strpos($attribs['display'],'meta')!==false;
		
		$this->cfg = $attribs;
		unset($this->cfg['pageToken']);
		unset($this->cfg['infinite_scroll']);
		
		$this->attribs = $attribs;
	}
	
}