<?php

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

class I24hVod extends AbstractVod
{
    private $session;
    private $tv;
    
    public function __construct($session, $tv)
    {
        parent::__construct(
            I24hConfig::VOD_FAVORITES_SUPPORTED,
            I24hConfig::VOD_MOVIE_PAGE_SUPPORTED,
            false);
        $this->session = $session;
        $this->tv = $tv;
    }


    public function get_vod_stream_url($playback_url, &$plugin_cookies)
    {
//        hd_print("------------  playback_url -----------");
//        hd_print(print_r($playback_url,true));
//        hd_print("------------  plugin_cookies -----------");
//        hd_print(print_r($plugin_cookies,true));
//        hd_print("----------------------------------------");
//        hd_print("i24h_vod.php get_vod_stream_url");

        list($type, $season, $serie_id, $potok) = explode(";", $playback_url);
        if ($type === 'VIDEO_EPISODES_URL') {

            $eps = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_EPISODES_URL,
                $season, $serie_id, $potok, $this->session->get_token()));

            if (is_null($eps))
                throw new Exception('Can not fetch topmovie list');
            $xml_eps = simplexml_load_string($eps);

            if ($xml_eps === false) {
                hd_print("Error: can not parse XML document.");
                hd_print("XML-text: $eps.");
                throw new Exception('Illegal XML document');
            }

            if ($xml_eps->getName() !== 'root') {
                hd_print("Error: unexpected node '" . $xml_eps->getName() . "'. Expected: 'response'");
                throw new Exception('Invalid XML document');
            }

            return strval($xml_eps->hls);

        }

        if ($type === 'VIDEO_STREAM') {

            $video = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_STREAM,
                $season, $potok, $this->session->get_token()));

            if (is_null($video))
                throw new Exception('Can not fetch topmovie list');
            $xml_video = simplexml_load_string($video);

            if ($xml_video === false) {
                hd_print("Error: can not parse XML document.");
                hd_print("XML-text: $video.");
                throw new Exception('Illegal XML document');
            }

            if ($xml_video->getName() !== 'root') {
                hd_print("Error: unexpected node '" . $xml_video->getName() . "'. Expected: 'response'");
                throw new Exception('Invalid XML document');
            }
            return strval($xml_video->hls);
        }
    }

    public function try_load_movie($movie_id, &$plugin_cookies)
    {
//        hd_print("try_load_movie !!!!!!!!!!!!!!!!!!!!!!!!!!");
    	$this->session->ensure_logged_in($plugin_cookies);
    	$this->tv->ensure_channels_loaded($plugin_cookies);

        $doc =
            HD::http_get_document(
                sprintf(
                    $this->session->get_api_server() . I24hConfig::MOVIE_INFO_URL_FORMAT,
                    $movie_id, $this->session->get_token()));
     
        if (is_null($doc))
            throw new Exception('Can not fetch movie info');

        $xml = simplexml_load_string($doc);

        if ($xml === false)
        {
            hd_print("Error: can not parse XML document.");
            hd_print("XML-text:\n$doc\n");
            throw new Exception('Illegal XML document');
        }

        if ($xml->getName() !== 'root')
        {
            hd_print("Error: unexpected node '" . $xml->getName() .
                "'. Expected: 'movie_info'");
            throw new Exception('Invalid XML document');
        }

        $movie = new Movie($xml->id);

        $poster="";
        foreach ($xml->img->children() as $i){
            if (strval($i->type) == "poster"){
                $poster = strval($i->src);
                break;
            }
        }

        $frame = "";
        foreach ($xml->img->children() as $i){
            if (strval($i->type) == "frame"){
                $frame = strval($i->src);
                break;
            }
        }
        $img_src = !empty($poster)?$poster:$frame;

        $ganres = array();
        foreach ($xml->genres->children() as $g){
            $ganres[] = strval($g->name);
        }
        $ganre=implode(', ', $ganres);

        $countrya = array();
        foreach ($xml->countries->children() as $g){
            $countrya[] = strval($g->name);
        }
        $country = implode(', ', $countrya);
        $movie->set_data(
            strval($xml->title),
            '',
            strval($xml->description),
            $img_src,
            '',
            strval($xml->year),
            '',
            '',
            '',
            $ganre,
            $xml->rating_imdb,
            $xml->rating_kinopoisk,
            strval($xml->age),
            $country,
            ''
            );

        $doc2 =
            HD::http_get_document(
                sprintf(
                    $this->session->get_api_server() . I24hConfig::MOVIE_SERIES_URL_FORMAT, $movie_id, $this->session->get_token()));
     
        if (is_null($doc2))
            throw new Exception('Can not fetch movie info');

        $xml = simplexml_load_string($doc2);

        if ($xml === false)
        {
            hd_print("Error: can not parse XML document.");
            hd_print("XML-text:\n$doc2\n");
            throw new Exception('Illegal XML document');
        }

        if ($xml->getName() !== 'root')
        {
            hd_print("Error: unexpected node '" . $xml->getName() .
                "'. Expected: 'response'");
            throw new Exception('Invalid XML document');
        }

        $date_loaded = false;
        foreach ($xml as $item)
        {
            $bgn = strftime("%d.%m.%Y %H:%M", intval($item->timestamp));

            if (intval(strval($item->timestamp)) <= time()) {
            	if (!$date_loaded) { 
            	    $date_loaded = true;
            	};
                $poster = "";
            	foreach ($item->program->img->children() as $i){
            	    if (strval($i->type) == "poster"){
                        $poster = strval($i->src);
                        break;
                    }
                }
                $frame = "";
            	foreach ($item->program->img->children() as $i){
            	    if (strval($i->type) == "frame"){
                        $frame = strval($i->src);
                        break;
                    }
                }
                $img_src = !empty($poster)?$poster:$frame;
                $channel = $this->tv->get_channel(strval($item->channel->id));
            	$movie->add_series_data(
            	    $item->id,
            	    $bgn.' '.($channel->get_title()).': '.mb_substr(strval($item->program->short), 0, 80, "UTF-8").'...' ,
            	    MediaURL::encode(
            	    	array(
            	    	    'channel_id' => strval($item->channel->id),
            	    	    'group_id' => '__all_channels',
            	    	    'archive_tm' => strval($item->timestamp),
                            'streaming_url' => $channel->get_streaming_url(),
                            'tariffs' => $channel->get_tariffs($item->channel->id),
                            'channel_name' => strval($item->channel->name),
            	    	    )),
            	    
            	    true,
                     $channel->get_icon_url()
            	    );
            }
        }
        $this->set_cached_movie($movie);
    }

    public function get_channel($channel_id){
        $channel = $this->tv->get_channel($channel_id);
        return $channel;
    }

    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);
    }

    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);
    }

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

    public function get_vod_list_folder_views()
    {
        return I24hConfig::GET_VOD_MOVIE_LIST_FOLDER_VIEWS();
    }
}
?>
