<?php

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

class I24hAmediaVod extends AbstractVod
{
    private $session;
    const ID = 'amedia_vod';
    
    public function __construct($session)
    {
        parent::__construct(
            I24hConfig::VOD_FAVORITES_SUPPORTED,
            I24hConfig::VOD_MOVIE_PAGE_SUPPORTED,
            true);
        $this->session = $session;
    }

    public function try_load_movie($season_id, &$plugin_cookies)
    {

        if (I24hConfig::DEBUG) hd_print("!!!!!!!!!!!!  try_load_movie !!!!!!!!!!!!!!!! ");
    	$this->session->ensure_logged_in($plugin_cookies);

        $url = sprintf(
            $this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST,
            $this->session->get_token(), $season_id);
        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);

        $movie->set_data(
            $doc->name,
            '', //$this->tv->get_channel(strval($xml->channels_id))->get_title(), //$xml->caption_original,
            $doc->desc,
            $doc->img->file->url,
            '', //round(($xml->etm - $xml->tm)/60),
            $doc->year,
            '', //$xml->director,
            '', //$xml->scenario,
            '', //$xml->actors,
            '', //$xml->genres,
            '', //$xml->imdb,
            '', //$xml->kinopoisk,
            $doc->age,
            '', //$xml->country,
            '' //$xml->budget
            );

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

        $date_loaded = false;
        foreach ($doc as $item)
        {
            if (intval(strval($item->tm)) <= time()) {
            	if (!$date_loaded) { 
            	    $movie->name_original .= ', '.strval($item->bgn);
            	    $date_loaded = true;
            	};
            	
            	$bgn = strftime("%m.%d %H:%M", intval($item->tm));

            	$movie->add_series_data(
            	    $item->id,
            	    $bgn.' '.($this->tv->get_channel(strval($item->channels_id))->get_title()).': '.(strval($item->subtitle) ? strval($item->subtitle) : mb_substr(strval($item->descshort), 0, 80, "UTF-8").'...' ), 
            	    MediaURL::encode(
            	    	array(
            	    	    'channel_id' => strval($item->channels_id),
            	    	    'group_id' => '__all_channels',
            	    	    'archive_tm' => strval($item->tm)
            	    	    )),
            	    
            	    true,
            	    preg_replace('/\/res\//', "/resize/320x200/res/", strval($item->img->file->url))
            	    );
            }
        }

        $this->set_cached_movie($movie);
    }

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

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

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

?>
