<?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)
    {

        hd_print("!!!!!!!!!!!!  try_load_movie !!!!!!!!!!!!!!!! ");
    	$this->session->ensure_logged_in($plugin_cookies);

        $doc =
            HD::http_get_document(
                sprintf(
                    $this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST,
                    $this->session->get_token(), $movie_id));
     
        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() !== 'response')
        {
            hd_print("Error: unexpected node '" . $xml->getName() .
                "'. Expected: 'movie_info'");
            throw new Exception('Invalid XML document');
        }

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

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

           
        $doc2 =
            HD::http_get_document(
                sprintf(
                    $this->session->get_api_server() . I24hConfig::MOVIE_SERIES_URL_FORMAT,
                    $this->session->get_token(), $movie_id));
     
        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() !== 'response')
        {
            hd_print("Error: unexpected node '" . $xml->getName() .
                "'. Expected: 'response'");
            throw new Exception('Invalid XML document');
        }

        $date_loaded = false;
        foreach ($xml 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();
    }
}

?>
