<?php
///////////////////////////////////////////////////////////////////////////

require_once 'lib/vod/abstract_vod.php';
require_once 'lib/vod/movie.php';

///////////////////////////////////////////////////////////////////////////

class MyPlugIN_Vod extends AbstractVod
{
    private $session;
    public function __construct($session)
    {
        parent::__construct(
            MyPlugIN_Config::VOD_FAVORITES_SUPPORTED,
            MyPlugIN_Config::VOD_MOVIE_PAGE_SUPPORTED,
            true);
	$this->session = $session;
    }

    ///////////////////////////////////////////////////////////////////////

    	public function try_load_movie($movie_id, &$plugin_cookies)
	{
		$this->session->check_login($plugin_cookies);
		$data = $this->session->get_vod_info($movie_id);
		hd_print("MOVIE-------------$movie_id");
		if (preg_match('/karaoke/i', $movie_id))
		{
			$movie = new Movie('karaoke'.intval($data->results->id));
			$movie->set_data(
						strval($data->results->name),
						'',//strval($data->results->original_name),
						strip_tags($data->results->performer),
						'plugin_file://icons/karaoke1.png',
						'',//$data->results->lenght,
						'',//$data->results->year,
						'',//$data->results->director,
						'',//writer
						'',//$data->results->actors,
						'',//$data->results->genres_ids,
						'',//imdb
						'',//kinopoisk
						'',//mpaa
						'',//$data->results->country,
						'');//$data->results->budget);
			//$url = $this->session->get_vod_url($data->results->id);
			$url = strval($data->results->url);		
			$url = str_ireplace("http://","http://mp4://",$url);
			hd_print(" ---- url_vod:$url");
			$movie->add_series_data(
								'karaoke'.intval($data->results->id),
								1,
								'karaoke'.intval($data->results->id),
								false);
			$this->set_cached_movie($movie);
		}
		else
		{
			hd_print("-------------------jetzt");
			$movie = new Movie(intval($data->results->id));
			$movie->set_data(
						//strval($data->results->name),
						strval($data->results->original_name),
						strval($data->results->original_name),
						strip_tags($data->results->description),
						strval($data->results->cover),
						'',//$data->results->lenght,
						$data->results->year,
						$data->results->director,
						'',//writer
						$data->results->actors,
						$data->results->genres,
						'',//imdb
						$data->results->rating_imdb,
						'',//kinopoisk
						$data->results->rating_kinopoisk,
						'',//mpaa
						'',//$data->results->country,
						'');//$data->results->budget);
			if($data->results->series)
			{
				foreach($data->results->series as $serie)
				{
					//$url = $this->session->get_vod_serie_url($data->results->id, $serie);
					//$url = $url->results;		
					//$url = str_ireplace("http://","http://mp4://",$url);
					//hd_print("  url_vod:-----------");
					$movie->add_series_data(
										intval($data->results->id).'-'.intval($serie),
										intval($serie).' Серия',
										intval($data->results->id).'/episodes/'.intval($serie),
										false);
					//}
					$this->set_cached_movie($movie);
				}
			}
			else
			{
				$url = $this->session->get_vod_url($data->results->id);
				$url = $url->results;
				$url = str_replace('http://ts://', 'http://', $url);
				//подменяем сервер
				if (isset($plugin_cookies->stream_server))
				{
					$PARSE=parse_url($url);
					$url=str_replace($PARSE["host"], $plugin_cookies->stream_server, $url);
				}
				
				if(preg_match('/\.m3u8/i', $url))
				{
					$url = $url;
				}
				elseif(preg_match('/.mp4/i', $url))
				{
					$url = str_replace('http://', 'http://mp4://', $url);
				}
				elseif(preg_match('/\.mkv/i', $url))
				{
					$url = $url;
				}
				elseif(preg_match('/\.avi/i', $url))
				{
					$url = $url;
				}
				hd_print("  url_vod: $url ----1");
				$movie->add_series_data(
									intval($data->results->id),
									'1',
									$url,
									true);
				$this->set_cached_movie($movie);
			}
		}
	}
	
	public function get_vod_stream_url($playback_url, &$plugin_cookies)
	{
		//hd_print("playback_url:---------->$playback_url");
		if (preg_match('/karaoke/i', $playback_url))
		{
			$data = $this->session->get_vod_url($playback_url);
			$url = $data->results;
			if(preg_match('/http:\/\/www.ex.ua/i', $url))
			{
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8");
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, TRUE);
				#curl_setopt($ch, CURLOPT_REFERER, $url);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
				$a = curl_exec($ch);
				if(preg_match('#Location: (.*)#', $a, $r))
				{
					$m_url = trim($r[1]);
					hd_print("url_location----->$m_url");
				}
				curl_close($ch);
				if(preg_match('/\.avi/i', $m_url))
					$url = urldecode($m_url);
				elseif(preg_match('/\.mkv/i', $m_url))
					$url = urldecode($m_url);
				elseif(preg_match('/.mp4/i', $url))
					$url = urldecode(str_replace('http://', 'http://mp4://', $url));
			}
			elseif(preg_match('/.mp4/i', $url))
				$url = str_replace('http://', 'http://mp4://', $url);
			elseif(preg_match('/\.mkv/i', $url))
				$url = $url;
			elseif(preg_match('/\.avi/i', $url))
				$url = $url;
			hd_print("---------$url");
			return $url;
		}
		else
		{
			$url = $this->session->get_vod_url($playback_url);
			$url = $url->results;
			if(preg_match('/.mp4/i', $url))
				$url = str_replace('http://', 'http://mp4://', $url);
			elseif(preg_match('/\.mkv/i', $url))
				$url = $url;
			elseif(preg_match('/\.avi/i', $url))
				$url = $url;
			$url = str_replace('http://', 'http://ts://', $url);
			hd_print("url_vod: $url");
			return $url;
		}
	}


    public function get_vod_info(MediaURL $media_url, &$plugin_cookies)
    {
       	$movie = $this->get_loaded_movie($media_url->movie_id,$plugin_cookies);
	if ($movie === null)
        {
    	    return null;
        }
        $sel_id = isset($media_url->series_id) ? $media_url->series_id : null;
        $buff = 500;//$plugin_cookies->buf_time;
        hd_print("buffer:$buff");
        return $movie->get_vod_info($sel_id,$buff);
    }

    ///////////////////////////////////////////////////////////////////////
    // Genres.


    protected function load_genres(&$plugin_cookies)
    {
	$this->session->check_login($plugin_cookies);
	$cat = $this->session->get_vod_cat($plugin_cookies);
        $data = $this->session->get_vod_genres();	
        $genres = array();
	$genres["all_categories"] = 'Все категории';
	foreach ($cat->results as $genre)
	{
        $genres[$genre->id.'cat-andy555'] = strval($genre->title);
	    hd_print("dddd-----:$genre->id - $genre->title - $genre->id .png");
	}
        foreach ($data->results as $genre)
	{
        $genres[$genre->id] = strval($genre->title);
	    hd_print("dddd-----:$genre->id - $genre->title - $genre->id .png");
	}
        return $genres;
    }


    public function get_genre_icon_url($genre_id)
    {
        return $this->session->get_icon_genre('vod_pop.png');
    }

    public function get_genre_media_url_str($genre_id)
    {
        return MyPlugIN_VodListScreen::get_media_url_str('genres', $genre_id);
    }


	public function get_vod_genres_folder_views()
    {
        $mov_genre_default_icon_url = $this->session->get_icon_genre('vod_pop.png');

        return array(
            array
            (
                PluginRegularFolderView::async_icon_loading => false,

                PluginRegularFolderView::view_params => array
                (
                    ViewParams::num_cols => 3,
                    ViewParams::num_rows => 10,
					ViewParams::background_path=> 'plugin_file://icons/bg.jpg',
					ViewParams::background_order => 0,
                ),

                PluginRegularFolderView::base_view_item_params => array
                (
                    ViewItemParams::item_padding_top => 0,
                    ViewItemParams::item_padding_bottom => 0,
                    ViewItemParams::icon_valign => VALIGN_CENTER,
                    ViewItemParams::item_layout => HALIGN_LEFT,
                    ViewItemParams::item_caption_width => 385,
                    ViewItemParams::icon_dx => 45,
                    ViewItemParams::icon_width => 49,
                    ViewItemParams::icon_height => 43,
                ),

                PluginRegularFolderView::not_loaded_view_item_params => array
                (
                    ViewItemParams::icon_path => $mov_genre_default_icon_url,
                ),
            ));
    }
    ///////////////////////////////////////////////////////////////////////
    // Favorites.

    protected function load_favorites(&$plugin_cookies)
    {
        $fav_movie_ids = $this->get_fav_movie_ids_from_cookies($plugin_cookies);

        foreach ($fav_movie_ids as $movie_id)
        {
            if ($this->has_cached_short_movie($movie_id))
                continue;
            $this->ensure_movie_loaded($movie_id, $plugin_cookies);
        }
        $this->set_fav_movie_ids($fav_movie_ids);

        hd_print('The ' . count($fav_movie_ids) . ' favorite movies loaded.');
    }

    protected function do_save_favorite_movies(&$fav_movie_ids, &$plugin_cookies)
    {
        $this->set_fav_movie_ids_to_cookies($plugin_cookies, $fav_movie_ids);
    }

    ///////////////////////////////////////////////////////////////////////

    public function get_fav_movie_ids_from_cookies(&$plugin_cookies)
    {
        if (!isset($plugin_cookies->{'favorite_movies'}))
            return array();

        $arr = preg_split('/,/', $plugin_cookies->{'favorite_movies'});

        $ids = array();
        foreach ($arr as $id)
        {
            if (preg_match('/\S/', $id))
                $ids[] = $id;
        }
        return $ids;
    }

    public function set_fav_movie_ids_to_cookies(&$plugin_cookies, &$ids)
    {
	$plugin_cookies->favorite_movies = join(',', $ids);
    }

    ///////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////
    // Search.


    public function get_search_media_url_str($pattern)
    {
        return MyPlugIN_VodListScreen::get_media_url_str('search', $pattern);
    }


    ///////////////////////////////////////////////////////////////////////
    // Folder views.

    public function get_vod_list_folder_views()
    {
        return MyPlugIN_Config::GET_VOD_MOVIE_LIST_FOLDER_VIEWS();
    }

    public function get_archive(MediaURL $media_url)
    { 
        return $this->session->get_archive();
    }
    
    public function get_vod_search_folder_views()
    {
        return MyPlugIN_Config::GET_TEXT_ONE_COL_VIEWS();
    }
    
    
}

///////////////////////////////////////////////////////////////////////////
?>
