<?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)
    {
        list($type, $season, $serie_id, $potok) = explode(";", $playback_url);
        if ($type === 'VIDEO_EPISODES_URL') {

            $url = sprintf($this->session->get_api_server() . I24hConfig::VIDEO_EPISODES_URL,
                $season, $serie_id, $potok, $this->session->get_token());
            try {
                $doc = $this->session->api_call($url);
            } catch (Exception $e) {
                throw new DuneException(
                    'HTTP network error', 0,
                    ActionFactory::show_error(
                        true,
                        'Ошибка связи',
                        array('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
            }
            return strval($doc->hls);

        }

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

            $url = sprintf($this->session->get_api_server() . I24hConfig::VIDEO_STREAM,
                $season, $potok, $this->session->get_token());
            try {
                $doc = $this->session->api_call($url);
            } catch (Exception $e) {
                throw new DuneException(
                    'HTTP network error', 0,
                    ActionFactory::show_error(
                        true,
                        'Ошибка связи',
                        array('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
            }

            return strval($doc->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);

    	$url = sprintf($this->session->get_api_server() . I24hConfig::MOVIE_INFO_URL_FORMAT, $movie_id, $this->session->get_token());
        try {
            $doc = $this->session->api_call($url);
        } catch (Exception $e) {
            throw new DuneException(
                'HTTP network error', 0,
                ActionFactory::show_error(
                    true,
                    'Ошибка связи',
                    array('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
        }

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

        $frame = '';
        $poster = '';
        $cover = '';
        foreach ($doc->img as $i) {
            if ($i->type == 'poster' && $i->ar == '2:3') {
                $poster = strval($i->src);
            }elseif ($i->type == 'frame'){
                $frame = strval($i->src);
            }elseif ($i->type == 'cover'){
                $cover = strval($i->src);
            }
        }
        if (!empty($poster)){
            $img = $poster;
        }elseif (!empty($cover)){
            $img = $cover;
        }else{
            $img = $frame;
        }

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

        $countrya = array();
        foreach ($doc->countries as $g){
            $countrya[] = strval($g->name);
        }
        $country = implode(', ', $countrya);
        $movie->set_data(
            strval($doc->title),
            '',
            strval($doc->description),
            $img."?w=200&h=300&crop=true",
            '',
            strval($doc->year),
            '',
            '',
            '',
            $ganre,
            $doc->rating_imdb,
            $doc->rating_kinopoisk,
            strval($doc->age),
            $country,
            ''
            );

        $url2 = sprintf($this->session->get_api_server() . I24hConfig::MOVIE_SERIES_URL_FORMAT, $movie_id, $this->session->get_token());
        try {
            $doc2 = $this->session->api_call($url2);
        } catch (Exception $e) {
            throw new DuneException(
                'HTTP network error', 0,
                ActionFactory::show_error(
                    true,
                    'Ошибка связи',
                    array('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
        }

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

            if (intval(strval($item->timestamp)) <= time()) {
            	if (!$date_loaded) { 
            	    $date_loaded = true;
            	};
                $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();
    }
}
?>
