<?php

require_once 'lib/hashed_array.php';
require_once 'lib/tv/abstract_tv.php';
require_once 'lib/tv/default_epg_item.php';

require_once 'tv_channel.php';

class MyPlugINTv extends AbstractTv
{
	public $cookie = array();

	public function __construct($session)
	{
		parent::__construct(
			AbstractTv::MODE_CHANNELS_N_TO_M,
			MyPlugIN_Config::TV_FAVORITES_SUPPORTED,
			true);
		$this->session = $session;
	}

	public function get_fav_icon_url()
	{
		return 'plugin_file://icons/genres/fav.png';
	}
	public function get_all_icon_url()
	{
		return 'plugin_file://icons/genres/all.png';
	}

	public function newload(&$plugin_cookies)
	{
		if(is_null($this->channels) && is_null($this->groups))
			$this->load_channels($plugin_cookies);
	}

	/**
	 * @param $plugin_cookies
	 */
	protected function load_channels(&$plugin_cookies)
	{
		$this->session->check_login($plugin_cookies);
		$this->channels = new HashedArray();
		$this->groups = new HashedArray();
		$group_tmp = null;
		$buffer = isset($plugin_cookies->buf_time) ? $plugin_cookies->buf_time : 0;
		$hide_category_items = isset($plugin_cookies->hide_category_items) ? $plugin_cookies->hide_category_items : '';
$tmp_hide_category_items = explode('|', $hide_category_items);
		$hide_items = isset($plugin_cookies->hide_items) ? $plugin_cookies->hide_items : '';
		$hided_channels = isset($plugin_cookies->hided_channels) ? $plugin_cookies->hided_channels : 'no';
		if ($this->is_favorites_supported())
		{
			$this->groups->put(new FavoritesGroup($this,
			'__favorites',
			'Избранные',
			$this->get_fav_icon_url()));
		}
		$this->groups->put( new AllChannelsGroup($this,
		'Все каналы',
		$this->get_all_icon_url()));
		
		$this->session->get_smart_token($plugin_cookies);
		$post_data="platform=smartup&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token;		
		$playlist=json_decode(HD::http_post_document("http://smart.prostotv.com/smartup/tv/playlist", $post_data));
		
		$post_data="platform=smartup&duid=" . $plugin_cookies->duid . "&lid=ru&token=" . $plugin_cookies->smart_token . "&prefix=tv";
		$BBB=json_decode(HD::http_post_document("http://smart.prostotv.com/smartup/lang", $post_data));

		foreach($BBB->tv->groups as $k=>$group)
		{
			if ($k == "all" || $k == "favorites")
			continue;
			$groups[$k] = $group;//формируем группу с понятными названиями
		}

		foreach ($playlist->playlist->groups as $tv_category)
		{
DuneSystem::$properties["cats_prostotv"][$tv_category->id] = $groups[$tv_category->title];

if (in_array($tv_category->id, $tmp_hide_category_items))
continue;
			$this->groups->put( new DefaultGroup(
			$tv_category->id,
			$groups[$tv_category->title],
			'plugin_file://icons/genres/'. strval($tv_category->title) .'.png'));
		}
		
		foreach ($playlist->playlist->channels as $channels)
		{
			$logo = "http://smart.prostotv.com/smartup" . substr($channels->logo, 1);
			$stalker_channel = new MyPlugIN_Channel(
			intval($channels->id),
			strval($channels->name),
			strval($logo),
			strval($channels->url),
			//intval($channels->archive_range) / 24,
			30,
			4,
			$buffer,
			intval($channels->censored),
			intval($channels->archive),
			"");
			
			########hide########
			if($hided_channels == 'no')
			{
				$ch = strval($channels->id);
				$t = ListUtil::is_in_list($hide_items, $ch);
				if ($ch == $t) continue;
			}
			
			foreach ($playlist->playlist->groups as $tv_category)
			{
				if (in_array($tv_category->id, $tmp_hide_category_items))
				continue;
				if ($tv_category->id == $channels->group)
				{
					$this->channels->put($stalker_channel);
					$group = $this->groups->get($tv_category->id);
					$stalker_channel->add_group($group);
					$group->add_channel($stalker_channel);
				}
			}	
		}
	}

	public function get_tv_playback_url($channel_id,$archive_ts,$protect_code,&$plugin_cookies)
	{

$url = $this->get_channel($channel_id)->get_streaming_url();

//		$this->ensure_channels_loaded($plugin_cookies);
//		$this->session->check_login($plugin_cookies);	
//		$account_settings = $this->session->get_account_settings();
//		$pass_sex = $account_settings->results->parent_password;
//		$nado = $this->get_channel($channel_id)->is_protected();

/*		
		if($nado)
		{
			if ($protect_code != $pass_sex)
				$url = 'protected';
			else
				$url = $this->session->get_url($channel_id,$archive_ts,$protect_code,&$plugin_cookies);
		}
		else
			$url = $this->session->get_url($channel_id,$archive_ts,$protect_code,&$plugin_cookies);
*/
			
		if (intval($archive_ts) > 0)
//////////////////////////////////////////////////АРХИВ/////////////
		 {
			$now_ts = time();
			$utcend = (($now_ts - $archive_ts)>=14400)? ($archive_ts + 14400) : $now_ts;
			if (strpos($url, "mpegts") !== false)
			{
				$url=str_replace("mpegts", "timeshift_abs-$archive_ts.ts", $url);
				$url=str_replace("http://", "http://ts://", $url);
				$url = $url . "|||dune_params|||psi_opt:2,ss_for_http_ts:1,keep_pic:0";
			}
			else
			{
				$url = str_replace(array("video.m3u8", "mono.m3u8", "index.m3u8"), array("video-$archive_ts-14400.m3u8", "mono-$archive_ts-14400.m3u8", "video-$archive_ts-14400.m3u8"), $url);
				$url=str_replace("http://", "http://ts://", $url);
			}		
		}
		else///ПРЯМОЙ
		{
			if (strpos($url, "mpegts") !== false)
			{
				//$url=str_replace("http://", "http://ts://", $url);
				$url = $url . "|||dune_params|||psi_opt:2,ss_for_http_ts:1,keep_pic:0";
			}
			else
			{
				$url=str_replace("http://", "http://ts://", $url);
			}		
		}
		echo ("Start............. " . $url);
		return $url;
	}
	
	public function get_day_epg_iterator($channel_id, $day_start_ts, &$plugin_cookies)
	{
		$epg = array();
		$epg_shift = isset($plugin_cookies->epg_shift) ? $plugin_cookies->epg_shift : 0;
		$post_data="platform=smartup&duid=$plugin_cookies->duid&lid=ru&token=$plugin_cookies->smart_token&module=tv&cid=$channel_id&get=day&time=$day_start_ts";
		$doc=HD::http_post_document("http://smart.prostotv.com/smartup/tv/epg/channel", $post_data);
		if ($doc == "")
		{
			$epg[] =
			new DefaultEpgItem(
			"ТВ Программа отсутствует!",
			"",
			"",
			0);
		}
		else
		{
			$doc = json_decode($doc);
			foreach ($doc->day as $epg_item)
			{
				if ($epg_item->desc == "")
					$desc=strval($epg_item->name);
				else
					$desc=strval($epg_item->desc);
				$epg[] =
				new DefaultEpgItem(
				strval($epg_item->name),
				$desc,
				intval($epg_item->start),
				intval($epg_item->stop));
			}
		}
		return new EpgIterator(
		$epg,
		$day_start_ts,
		$day_start_ts + 86400 * 7);
	}
	
	

	public function get_day_epg_iterator_old($channel_id, $day_start_ts, &$plugin_cookies)
	{
		$epg = array();
		$epg_shift = isset($plugin_cookies->epg_shift) ? $plugin_cookies->epg_shift : 0;
		$xml = $this->session->get_stalker_epg($day_start_ts,$channel_id,$this->cookie,&$plugin_cookies);
		if ($xml->status !== 'OK')
		{
			$epg[] =
			new DefaultEpgItem(
			"ТВ Программа отсутствует!",
			"",
			"",
			0);
		}
		else
		{
			foreach ($xml->results as $epg_item)
			{
				#print_r($epg_item);
				$epg[] =
				new DefaultEpgItem(
				strval($epg_item->name),
				//strval($epg_item->id),
				strval($epg_item->name),
				intval($epg_item->start),
				intval($epg_item->end));		
			}
		}		
		return new EpgIterator(
		$epg,
		$day_start_ts,
		$day_start_ts + 86400 * 7);
	}

	public function get_archive(MediaURL $media_url)
	{ 
		return $this->session->get_archive();
	}
	
    public function add_special_groups(&$items)
    {
        array_push($items,
            array
            (
                PluginRegularFolderItem::media_url =>
                    MediaURL::encode(
                        array
                        (
                            'screen_id' => MyPlugIN_VodCategoryListScreen::ID,
                            'name' => 'VOD')),
                PluginRegularFolderItem::caption => 'Медиатека',
                PluginRegularFolderItem::view_item_params => array
                (ViewItemParams::icon_path =>"plugin_file://icons/vod.png")));
    }
	
	
	
	
}

?>
