<?php

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

class I24hVideoListScreen extends AbstractRegularScreen implements UserInputHandler
{

    public static function get_media_url_str($category_id, $id)
    {
        return MediaURL::encode(
            array
            (
                'screen_id' => $id,
                'category_id' => $category_id,
            ));
    }


    private $topcats;
    private $subcats;
    private $session;
    private $serials;
    private $genres;
    private $genres_tree;
    private $movies;
    private $toplist;
    private $id;
    private $filter_id;
    private $source_id;
    private $name;
    private $allow_view;
    private $allow_in_packets = array();
    private $lazy_limit = 20;
    private $is_need_label = false;
    private $BACKGROUND;
    private $TEMPLATE;

    public function __construct($session, $screen_id, $filter_id, $source_id, $name, $is_need_label = false,$background )
    {
        parent::__construct(
            $screen_id,
            array
            ());
        $this->session = $session;

        $subcats = array();
        $this->serials = array();
        $this->movides = array();
        $this->filter_id = $filter_id;
        $this->id = $screen_id;
        $this->source_id = $source_id;
        $this->name = $name;
        $this->is_need_label = $is_need_label;
        $this->BACKGROUND = $background;

        UserInputHandlerRegistry::get_instance()->register_handler($this);

    }

    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        if (isset($media_url->serieslist_id)) {
            $play_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'play_video');
            return array
            (
                GUI_EVENT_KEY_ENTER => $play_action,
                GUI_EVENT_KEY_PLAY => $play_action
            );
        } else {
            return array(GUI_EVENT_KEY_ENTER => ActionFactory::open_folder());
        }
    }


    public function get_handler_id(){
        return $this->id;
    }

    public function is_user_subcribers()
    {
        $this->allow_view = false;
        $cur_video = $this->session->get_current_videos();
        if ($cur_video[$this->source_id]) $this->allow_view = true;

        if (!$this->allow_view) {
            $pc=$this->session->get_videos_in_packets();
            unset($this->allow_in_packets);
            $this->allow_in_packets = $pc[$this->source_id];
        }
    }






    public function get_folder_range(MediaURL $media_url, $from_ndx,&$plugin_cookies)
    {

//        hd_print("-----------------------------");
//        hd_print("get_folder_range");
//        hd_print(print_r($media_url,true));
//        hd_print("-----------------------------");

        $this->session->ensure_logged_in($plugin_cookies);
        $count_video = 0;
        $items = array();

        if (isset($media_url->xcat_id)) {
            $subcats = $this->fetch_subcat_list($media_url->xcat_id,$from_ndx,$this->lazy_limit);
            foreach ($subcats as $m) {
                $items[] = array
                (
                    PluginRegularFolderItem::media_url => I24hVodListScreen::get_media_url_str($m['id'], $this->id),
                    PluginRegularFolderItem::caption => $m['name'],
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'
                    )
                );
            }

        } else if (isset($media_url->serieslist_id)) {

//            hd_print("media_url->serieslist_id = ".$media_url->serieslist_id);

            $movie = $this->get_loaded_series($media_url->serial_id, $media_url->serieslist_id, $plugin_cookies,$from_ndx,$this->lazy_limit);
            $i = 0;
            foreach ($movie->series_list as $s) {
                $s_mediaurl = MediaURL::encode(
                    array(
                        'screen_id' => $this->id,
                        'serial_id' => $media_url->serial_id,
                        'serieslist_id' => $media_url->serieslist_id,
                        'serie_id' => $s->id
                    ));
                $i++;
                $img = $this->is_need_label?($s->icon . "&video_label=true&id=" . $media_url->serial_id):($s->icon /*. "&crop=true"*/);
                $items[] = array
                (
                    PluginRegularFolderItem::media_url => $s_mediaurl,
                    PluginRegularFolderItem::caption => $s->name,
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => $img,
                    )
                );
                $count_video++;


            }
//            hd_print("Series list in season count = ".$count_video);
            return HD::create_regular_folder_range($items, $from_ndx, $count_video,false);

        } else if ((isset($media_url->serial_id)) && (isset($media_url->season_id))) {

        } else if (isset($media_url->serial_id)) {

            //hd_print("media_url->serial_id = ".$media_url->serial_id);

            // Вывод списка сезонов/серий/запуск видео
            $seasons = $this->getCountSeasons($media_url->serial_id);
            if ($seasons > 1){
                // Выводим список сезонов, их много

                $count_video = 0;
                $items = array();
                $serial = $this->fetch_serial($media_url->serial_id);

                $serial_desc = $serial['name'] . ", " . $serial['year'] . "\n" .
                    (!empty($serial['original']) ? "(" . $serial['original'] . ")\n" : "") . "\n" .
                    "Рейтинги:\n" .
                    'IMDB: ' . (!empty($serial['rating_imdb']) ? $serial['rating_imdb'] : "-") . "\n" .
                    'Кинопоиск: ' . (!empty($serial['kinopoisk']) ? $serial['kinopoisk'] : "-") . "\n" .
                    'MPAA: ' . (!empty($serial['age']) ? $serial['age'] . "+" : "");

                $sesons = $serial['seasons'];
                $seson = reset($sesons);
                $arr = preg_split("/;/", $seson['id']);

                if ($arr[1] > 0) {
                    foreach ($serial['seasons'] as $s) {
                        $mediaurl = MediaURL::encode(
                            array(
                                'screen_id' => $this->id,
                                'serial_id' => $media_url->serial_id,
                                'serieslist_id' => $s['id']
                            ));

                        $img = $serial['img'] . ($this->is_need_label ? "?w=320&h=200&video_label=true&id=" . $serial["id"] : "?w=320&h=200"); //&crop=true");
                        $items[] = array
                        (
//                            PluginRegularFolderItem::media_url =>
//                                VodMovieScreen::get_media_url_str($media_url->serial_id),
                            PluginRegularFolderItem::media_url => $mediaurl,
                            PluginRegularFolderItem::caption => $s['name'],
                            PluginRegularFolderItem::view_item_params => array(
                                ViewItemParams::item_detailed_icon_path => $img,
                                ViewItemParams::item_detailed_info => $serial_desc,

                            )
                        );
                        $count_video++;
                    }
                }
                $more = false;
                if ($count_video >= $this->lazy_limit){$more = true;}
//                hd_print("2 from_ndx = ".$from_ndx." this->lazy_limit = ".$this->lazy_limit." count_video = ".$count_video." more = ".$more);
                return HD::create_regular_folder_range($items, $from_ndx, $from_ndx+$count_video,$more);

            }else{

                $movie = $this->get_loaded_series($media_url->serial_id, $media_url->serial_id.";".$seasons, $plugin_cookies,$from_ndx,$this->lazy_limit);

                $i = 0;
                foreach ($movie->series_list as $s) {
                    $s_mediaurl = MediaURL::encode(
                        array(
                            'screen_id' => $this->id,
                            'serial_id' => $media_url->serial_id,
                            'serieslist_id' => $media_url->serieslist_id,
                            'serie_id' => $s->id
                        ));
                    $i++;
                    $img = $this->is_need_label?($s->icon . "&video_label=true&id=" . $media_url->serial_id):($s->icon /*. "&crop=true"*/);
                    $items[] = array
                    (
                        PluginRegularFolderItem::media_url => $s_mediaurl,
                        PluginRegularFolderItem::caption => $s->name,
                        PluginRegularFolderItem::view_item_params => array(
                            ViewItemParams::icon_path => $img,
                        )
                    );
                    $count_video++;
                }
//                hd_print("series list count =".$count_video);
                return HD::create_regular_folder_range($items, $from_ndx, $count_video,false);

            }

//        } else if ((isset($media_url->genre_id)) and (empty($this->genres[$media_url->genre_id]['count_filters']))) {
        } else if (isset($media_url->genre_id)){

            $t = $this->get_ganre_by_id($media_url->genre_id);

            if ($t["has_child"]){
                # Жанр задан, но есть детки
//                hd_print("Жанр задан, но есть детки");
                foreach ($this->get_parent_ganres($media_url->genre_id) as $g) {
                    $mediaurl = MediaURL::encode(
                        array(
                            'screen_id' => $this->id,
                            'genre_id' => $g['id']
                        ));
                    $items[] = array
                    (
                        PluginRegularFolderItem::media_url => $mediaurl,
                        PluginRegularFolderItem::caption => $g['name'],
                        PluginRegularFolderItem::view_item_params => array(
                            ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'//$g['img']
                        )
                    );
                }
                return HD::create_regular_folder_range(
                    $items, 0, count($items), false);


            }else{
//                'gui_skin://small_icons/folder.aai'
                # Жанр задан, нет деток, выводим сериалы

//                hd_print("Жанр задан, нет деток, выводим сериалы");

                $this->fetch_topmovie_list($media_url->genre_id, $from_ndx, $this->lazy_limit);
                foreach ($this->genres[$media_url->genre_id]['serials'] as $s) {
                    $mediaurl = MediaURL::encode(
                        array(
                            'screen_id' => $this->id,
                            'serial_id' => $s['id']
                        ));
                    $items[] = array
                    (
//                        PluginRegularFolderItem::media_url => $mediaurl,
                        PluginRegularFolderItem::media_url =>
                            VideoMovieScreen::get_media_url_str($this->id,$s['id'],$this->BACKGROUND),
                        PluginRegularFolderItem::caption => $s['name'],
                        PluginRegularFolderItem::view_item_params => array(
                            ViewItemParams::icon_path => $s['img'] . ($this->is_need_label ? '&video_label=true&id=' . $s['id'] : ''/*'&crop=true'*/)
                        )
                    );
                    $count_video++;
                }
            }



        } else {
            # Жанр не задан, выводим список жанров верхнего уровня
//            hd_print("Жанр не задан, выводим список жанров верхнего уровня");

//            $t = $this->get_ganre_by_id(0);

            //hd_print(print_r($t,true));

            switch ($this->TEMPLATE) {

                case "grid_w":
                    foreach ($this->get_parent_ganres(0) as $g) {
                        $mediaurl = MediaURL::encode(
                            array(
                                'screen_id' => $this->id,
                                'genre_id' => $g['id']
                            ));
                        $items[] = array
                        (
                            PluginRegularFolderItem::media_url => $mediaurl,
                            PluginRegularFolderItem::caption => $g['name'],
                            PluginRegularFolderItem::view_item_params => array(
                                ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'//$g['img']
                            )
                        );
                    }

                    break;
                case "grid_promo_w":
                    foreach ($this->get_parent_ganres(0) as $g) {
                        $mediaurl = MediaURL::encode(
                            array(
                                'screen_id' => $this->id,
                                'genre_id' => $g['id']
                            ));
                        $items[] = array
                        (
                            PluginRegularFolderItem::media_url => $mediaurl,
                            PluginRegularFolderItem::caption => $g['name'],
                            PluginRegularFolderItem::view_item_params => array(
                                ViewItemParams::icon_path => $g['img']
                            )
                        );
                    }
                    break;
                case "grid_v":
                    foreach ($this->get_parent_ganres(0) as $g) {
                        $mediaurl = MediaURL::encode(
                            array(
                                'screen_id' => $this->id,
                                'genre_id' => $g['id']
                            ));
                        $items[] = array
                        (
                            PluginRegularFolderItem::media_url => $mediaurl,
                            PluginRegularFolderItem::caption => $g['name'],
                            PluginRegularFolderItem::view_item_params => array(
                                ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'//$g['img']
                            )
                        );
                    }
                    break;
                case "grid_promo_v":
                    foreach ($this->get_parent_ganres(0) as $g) {
                        $mediaurl = MediaURL::encode(
                            array(
                                'screen_id' => $this->id,
                                'genre_id' => $g['id']
                            ));
                        $items[] = array
                        (
                            PluginRegularFolderItem::media_url => $mediaurl,
                            PluginRegularFolderItem::caption => $g['name'],
                            PluginRegularFolderItem::view_item_params => array(
                                ViewItemParams::icon_path => $g['img']
                            )
                        );
                    }
                    break;
                case "subfilters":
                    foreach ($this->get_parent_ganres(0) as $g) {
                        $mediaurl = MediaURL::encode(
                            array(
                                'screen_id' => $this->id,
                                'genre_id' => $g['id']
                            ));
                        $items[] = array
                        (
                            PluginRegularFolderItem::media_url => $mediaurl,
                            PluginRegularFolderItem::caption => $g['name'],
                            PluginRegularFolderItem::view_item_params => array(
                                ViewItemParams::icon_path => $g['img'].'?h=500'
                            )
                        );
                    }
                    break;

            }

//            $this->fetch_genre_tree();
            return HD::create_regular_folder_range(
                $items, 0, count($items), false);

        }
        $more = false;

//        hd_print("from_ndx = ".$from_ndx." this->lazy_limit = ".$this->lazy_limit." count_video = ".$count_video);
        if ($count_video >= $this->lazy_limit){$more = true;}
        return HD::create_regular_folder_range($items, $from_ndx, $from_ndx+$count_video,$more);
    }





    public function make_top_list($count)
    {
        $items = array();
//        hd_print("make_top_list");
//        $this->fetch_genre_list();
        $this->fetch_topmovie_list(null);
        $i = 1;

        foreach ($this->toplist as $s_id) {
            $s = $this->serials[$s_id];

            if ($s["type"] == 'video') {
                $mediaurl = MediaURL::encode(
                    array(
                        'screen_id' => $this->id,
                        'serial_id' => $s['id']
                    ));

                $items[] = array
                (
                    PluginRegularFolderItem::media_url => $mediaurl,
                    PluginRegularFolderItem::caption => $s['name'],
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => strval($s['img'])
                    )
                );
            }else if ($s["type"] == 'channel'){

                $items[] =  array
                (
                    PluginRegularFolderItem::media_url =>
                        MediaURL::encode(
                            array(
                                'channel_id' => $s["id"],
                                'group_id' => $s["id"])
                        ),


                    PluginRegularFolderView::actions => array
                    (
                    	GUI_EVENT_KEY_ENTER => ActionFactory::tv_play(),
                    	GUI_EVENT_KEY_PLAY  => ActionFactory::tv_play(),
                    	),
                    PluginRegularFolderItem::caption => $s['name'],
                    PluginRegularFolderItem::view_item_params => array
                    (
                        ViewItemParams::icon_path => strval($s['img'].'?w=320'),
                        ViewItemParams::item_detailed_icon_path => strval($s['img']),
                    )
                );
            }
            $i++;
            if ($i > $count) {
                break;
            }

        }
        return $items;
    }

    public function make_single_item($serial_id)
    {
//        $this->fetch_genre_list();
        $s = $this->fetch_serial($serial_id);
        if (empty($s)){return null;}

        if (!empty($s['type'])){

            if ($s['type'] == 'video') {
                $mediaurl = MediaURL::encode(
                    array(
                        'screen_id' => $this->id,
                        'serial_id' => $s['id']
                    ));
            } else if ($s['type'] == 'channel') {

                $mediaurl = MediaURL::encode(
                    array(
                        'channel_id' => $s->id,
                        'group_id' => 'all'
                    ));
            }
        }else{
            return null;
        }
        if ($s["source_id"]==1) {
            $img = strval($s['img'])."?w=320&h=200&video_label=true&id=".strval($s['id']);
        }else{
            $img = strval($s['img'])."?w=320&h=200&crop=true";
        }

        return array
        (
            PluginRegularFolderItem::media_url => $mediaurl,
            PluginRegularFolderItem::caption => $s['name'],
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => $img
            )
        );
    }


    private function fetch_topmovie_list($genre_id,$from_ndx = 0,$lazy_limit = 0)
    {
        if (!$genre_id) {

            $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_TOP_LIST, $this->session->get_token()));

            $this->toplist = array();
            if (is_null($doc))
                throw new Exception('Can not fetch topmovie list');
            $xml = simplexml_load_string($doc);

            if ($xml === false) {
                hd_print("Error: can not parse XML document.");
                hd_print("XML-text: $doc.");
                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');
            }

            foreach ($xml->children() as $c) {

                if (strval($c->destination->type) == 'program' or strval($c->destination->type) == 'video') {

                    $banner = $c->banner . "?w=320&h=200";
                    $doc2 = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_TOP_SERIAL_INFO, $c->destination->id, $this->session->get_token()));
                    if (is_null($doc2))
                        throw new Exception('Can not fetch topmovie list');
                    $xml2 = simplexml_load_string($doc2);

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

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

                    $poster = "";
                    foreach ($xml2->img->children() as $i) {
                        $poster = strval($i->src) . "?w=320&h=200";
                    }

                    if (1 == 1) {
                        $this->serials[strval($xml2->id)] = array(
                            'id' => strval($xml2->id),
                            'type' => 'video',
                            'name' => strval($xml2->title),
                            'year' => strval($xml2->year),
                            'descr' => strval($xml2->description),
                            'img' => $banner,
                            'seasons' => array()
                        );
                        $serial_id = $xml2->id;
                        $seasons = array();
                        foreach ($xml2->episodes->children() as $s) {
                            $seasons[$serial_id . ";" . $s->season] = $xml2->title;
                        }
                        foreach ($seasons as $k => $v) {
                            $chars = preg_split('/;/', strval($k));
                            $this->serials[strval($xml2->id)]['seasons'][strval($k)] = array(
                                'id' => strval($k),
                                'name' => "Сезон " . $chars[1],
                                'year' => '',
                                'descr' => '',
                            );
                        }
                        $this->toplist[] = strval($xml2->id);
                    }
                }else if (strval($c->destination->type) == 'channel'){

                    $banner = $c->banner . "?w=320&h=200";

                    $this->serials[intval($c->destination->id)] = array(
                        'id' => intval($c->destination->id),
                        'type' => 'channel',
                        'name' => strval($c->title),
                        'descr' => strval($c->description),
                        'img' => $banner
                    );
                    $this->toplist[] = strval($c->destination->id);

                }
            }

        } else {
//            hd_print("fetch_topmovie_list");
//            if (!isset($this->genres)) $this->fetch_genre_list();
            if (!isset($this->genres)) $this->fetch_genre_tree();

            $this->genres[$genre_id]['serials'] = array();
            $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIALS_LIST, $this->session->get_token(), $genre_id, $lazy_limit, $from_ndx));

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

            if ($xml === false) {
                hd_print("Error: can not parse XML document.");
                hd_print("XML-text: $doc.");
                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');
            }

            $count_video = 0;
            foreach ($xml->children() as $c) {

                if (!isset($this->serials[strval($c->id)])) {

                    $poster = "";
                    foreach ($c->img->children() as $i) {
                        $poster = strval($i->src) . "?w=320&h=200";
                    }
                    $this->serials[strval($c->id)] = array(
                        'id' => strval($c->id),
                        'name' => strval($c->title),
                        'year' => strval($c->year),
                        'original' => strval($c->original),
                        'rating_imdb' => strval($c->rating_imdb),
                        'rating_kinopoisk' => strval($c->rating_kinopoisk),
                        'age' => strval($c->age),
                        'descr' => strval($c->description),
                        'img' => $poster,
                        'seasons' => array()
                    );
                    $serial_id = $c->id;
                    $seasons = array();
                }
                $this->genres[$genre_id]['serials'][] = $this->serials[strval($c->id)];
            }
        }
    }


    private function fetch_genre_tree()
    {
        $this->genres_tree = array();
        $headers = array();
        $headers[] = 'Accept: application/xml';
        $headers[] = 'Content-Type: application/xml';
        $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_GENRE_LIST, $this->session->get_token()));

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

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

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

        foreach ($xml->children() as $m) {
            if ($m->id == $this->filter_id) {
//                $this->BACKGROUND = strval($m->image)."?w=1280&h=720";
                $this->TEMPLATE = strval($m->template);
                foreach ($m->filters->children() as $l) {
                    $this->genres_tree[] = array(
                        'id' => strval($l->id),
                        'name' => strval($l->name),
                        'img' => strval($l->image),
                        'template' => strval($l->template),
                        'parent' => 0,
                        'serials' => array(),
                        'has_child' => count($l->filters->children())>0?1:0
                    );
                    $count=0;
                    foreach ($l->filters->children() as $c) {
                        $count++;
                        $this->genres_tree[] = array(
                            'id' => strval($c->id),
                            'name' => strval($c->name),
                            'img' => strval($c->image),
                            'template' => strval($c->template),
                            'parent' => strval($l->id),
                            'serials' => array(),
                            'has_child' => 0
                        );
                    }


                }
            }
        }

    }

    private function get_parent_ganres($id = 0)
    {
        $ret_ar = array();
        foreach ($this->genres_tree as $t){
            if ($t["parent"] == $id){
                $ret_ar[] = $t;
            }
        }
        return $ret_ar;
    }

    private function get_ganre_by_id($id = 0)
    {
        foreach ($this->genres_tree as $t) {
            if ($t["id"] == $id) {
                return $t;
            }
        }
    }


    private function fetch_genre_list($ganre_id = 0 )
    {
//        hd_print("fetch_genre_list($ganre_id)");
        if (!empty($ganre_id)){

//           hd_print(print_r($this->genres[$ganre_id]['filters']->children(),true));

            $filters = $this->genres[$ganre_id]['filters'];
            $this->genres = array();

            foreach ($filters as $l) {
                $count=0;
                foreach ($l->filters->children() as $d){
                    $count++;
                }

                $this->genres[strval($l->id)] = array(
                    'id' => strval($l->id),
                    'name' => strval($l->name),
                    'img' => strval($l->image),//'gui_skin://small_icons/folder.aai',
                    'serials' => array(),
                    'filters' => $l->filters->children(),
                    'count_filters' => $count
                );
            }
//            hd_print("***********************************");
//            hd_print(print_r($this->genres,true));
//            hd_print("***********************************");


        }else {

            if (!isset($this->genres)) {
                $this->genres = array();
                $headers = array();
                $headers[] = 'Accept: application/xml';
                $headers[] = 'Content-Type: application/xml';
                $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_GENRE_LIST, $this->session->get_token())/*,array(CURLOPT_HTTPHEADER=>$headers)*/);

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

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

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


                $this->topcats = array();

//            hd_print(print_r($xml,true));
                foreach ($xml->children() as $c) {
                    if ($c->id == $this->filter_id) {
//                        $this->BACKGROUND = strval($c->image);
                        $this->TEMPLATE = strval($c->template);
//                        hd_print("BACKGROUND = " . $this->BACKGROUND);
                        foreach ($c->filters->children() as $l) {
//                            hd_print(print_r($l, true));

                            $this->genres[strval($l->id)] = array(
                                'id' => strval($l->id),
                                'name' => strval($l->name),
                                'img' => 'gui_skin://small_icons/folder.aai',
                                'serials' => array(),
                                'filters' => $l->filters->children(),
                                'count_filters' => count($l->filters->children())
                            );
                        }
                    }
                }
            }
        }
    }


    private function fetch_series_list($season_id,$from_ndx,$lazy_limit)
    {
        $series = array();
        $serils_seasons = preg_split('/;/', strval($season_id));

        $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST_LIMIT,
            $serils_seasons[0], $lazy_limit, $from_ndx, $this->session->get_token()));

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

        if ($xml === false) {
            hd_print("Error: can not parse XML document.");
            hd_print("XML-text: $doc.");
            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');
        }

        if (count($xml->children())>0) {
            foreach ($xml->children() as $c) {
                if ($c->season == $serils_seasons[1]) {

/*                    $eps = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_EPISODES_URL,
                        $serils_seasons[0], strval($c->id), 'hls', $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');
                    }
*/
                    $list_name = "";
                    if (strval($c->series) == 0) {
                        $list_name = ltrim(strval($c->list_title), '0. ');
                    } else {
                        $list_name = strval($c->list_title);
                    }
                    $series[] = array(
                        'id' => strval($c->id),
                        'name' => strval($list_name),
                        'url' => 'VIDEO_EPISODES_URL;'.$serils_seasons[0].';'.strval($c->id).';hls',
                        'img' => strval($c->img) . "?w=320&h=200",
                    );
                }
            }
        }else{

            $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIAL,
                $serils_seasons[0], $this->session->get_token()));
            if (is_null($doc))
                throw new Exception('Can not fetch topmovie list');
            $xml = simplexml_load_string($doc);

            if ($xml === false) {
                hd_print("Error: can not parse XML document.");
                hd_print("XML-text: $doc.");
                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');
            }
/*

            $video = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_STREAM,
                $serils_seasons[0], 'hls', $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');
            }
*/
            $poser = '';
            foreach ($xml->img->children() as $i) {
                if ($i->type == 'poster') {
                    $poser = $i->src;
                    break;
                }
            }

            $series[] = array(
                'id' => $serils_seasons[0],
                'name' => strval($xml->title),
                'url' => 'VIDEO_STREAM;'.$serils_seasons[0].';0;hls',//strval($xml_video->hls),
                'img' => strval($poser) . "?w=320&h=200",
            );

        }
        return $series;
    }

    private function fetch_serial($serial_id)
    {
        try {

            $series = array();

            $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIAL, $serial_id, $this->session->get_token()));
            if (is_null($doc))
                throw new Exception('Can not fetch topmovie list');
            $xml = simplexml_load_string($doc);

            if ($xml === false) {
                hd_print("Error: can not parse XML document.");
                hd_print("XML-text: $doc.");
                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');
            }

            $poser = '';
            if (!empty($xml->img)) {
                foreach ($xml->img->children() as $i) {
                    if ($i->type == 'poster') {
                        $poser = $i->src;
                        break;
                    }
                }
            }
            $this->serials[strval($xml->id)] = array(
                'id' => strval($xml->id),
                'name' => strval($xml->title),
                'original' => strval($xml->original),
                'rating_imdb' => strval($xml->rating_imdb),
                'rating_kinopoisk' => strval($xml->rating_kinopoisk),
                'source_id' => strval($xml->source->id),
                'age' => strval($xml->age),
                'year' => strval($xml->year),
                'descr' => strval($xml->description),
                'img' => $poser,
                'seasons' => array()
            );

            if (!empty($xml->episodes)) {

                foreach ($xml->episodes->children() as $ep) {
                    if (!isset($ep->season)) {
                        continue;
                    }
                    $seasons[strval($xml->id) . ";" . strval($ep->season)] = strval($ep->list_title);
                }

            }else{
                $seasons[strval($xml->id) . ";0"] = strval($xml->title);
            }

            foreach ($seasons as $k => $v) {
                $arr = preg_split("/;/", $k);
                if ($arr[1] > 0) {
                    $this->serials[strval($xml->id)]['seasons'][strval($k)] = array(
                        'id' => strval($k),
                        'name' => 'Сезон ' . $arr[1],
                        'year' => strval($xml->year),
                        'descr' => strval($xml->description),
                        'img' => $poser,
                    );
                } else {
                    $this->serials[strval($xml->id)]['seasons'][strval($k)] = array(
                        'id' => strval($k),
                        'name' => strval($xml->title),
                        'year' => strval($xml->year),
                        'descr' => strval($xml->description),
                        'img' => $poser,
                    );

                }
            }

            return $this->serials[strval($xml->id)];
        } catch (Exception $e) {
            return null;
        }

    }

    public function get_topcst_list()
    {
        return $this->topcats;
    }

    public function get_loaded_series($serial_id, $season_id, &$plugin_cookies,$from_ndx,$lazy_limit)
    {

//        hd_print("get_loaded_series");
        $this->session->ensure_logged_in($plugin_cookies);
        if (isset($this->movies[$season_id])) {
            return $this->movies[$season_id];
        }
        $serial = $this->fetch_serial($serial_id);

//        hd_print("---------------------------");
//        hd_print(print_r($serial,true));
//        hd_print("---------------------------");

        $season = $serial['seasons'][$season_id];
        $series = $this->fetch_series_list($season_id,$from_ndx,$lazy_limit);

        $movie = new Movie($season_id);
        if ($serial['name'] != $season['name']) {
            $serial_seria_name = $serial['name'].". ".$season['name'];
        }else{
            $serial_seria_name = $season['name'];
        }
        $movie->set_data($serial_seria_name,
            $serial['original'],
            $season['descr'],
            $serial['img'],
            '',
            $season['year'],
            '',
            '',
            '',
            '',
            $serial['rating_imdb'],
            $serial['rating_kinopoisk'],
            $serial['age'],
            '',
            ''
        );

        foreach ($series as $s) {
            $movie->add_series_data(
                $s['id'],
                $s['name'],
                $s['url'],
                false,
                $s['img']
            );
        }
        $this->movies[$season_id] = $movie;

        return $movie;
    }

    public function get_movie_left_button_caption(
        MediaURL $media_url, &$plugin_cookies)
    {
        return null;
    }

    public function get_movie_left_button_action(
        MediaURL $media_url, &$plugin_cookies)
    {
        return null;
    }

    public function get_vod_info(MediaURL $media_url, &$plugin_cookies)
    {

//        hd_print("get_vod_info !!!!!!!!!!! ".print_r($media_url,true));

        $this->session->ensure_logged_in($plugin_cookies);

        if (!empty($media_url->movie_id)) {


            $media_url->serial_id = $media_url->movie_id;
            $seasons = $this->getCountSeasons($media_url->serial_id);
            $count_seasons = $seasons>0?1:0;
            $movie = $this->get_loaded_series($media_url->movie_id, $media_url->movie_id.";".$count_seasons, $plugin_cookies,0,$this->lazy_limit);

            $this->is_user_subcribers();
            if ($this->allow_view) {
                $need_req_pass = empty($plugin_cookies->need_password_sextv) ? 'no' : $plugin_cookies->need_password_sextv;

//                hd_print("---------------movie---------------------");
//                hd_print(print_r($movie,true));
//                hd_print("-----------------plugin_cookies-------------------");
//                hd_print(print_r($plugin_cookies,true));
//                hd_print("------------------------------------");


//                hd_print("movie->rate_mpaa = $movie->rate_mpaa | need_req_pass = $need_req_pass");

                if (($movie->rate_mpaa >= 18) and ($need_req_pass == 'yes')) {
//                    hd_print("Close video");
                    $movie = $this->get_loaded_series(0, "0;0", $plugin_cookies,0,$this->lazy_limit);
                }
            }else{
//                hd_print("Close video");
                $movie = $this->get_loaded_series(0, "0;0", $plugin_cookies,0,$this->lazy_limit);
            }

//            hd_print("media_url->serial_id  = $media_url->movie_id, media_url->serieslist_id = $media_url->serieslist_id, count_seasons = $count_seasons");

//            return null;


        }else {
            $movie = $this->get_loaded_series($media_url->serial_id, $media_url->serieslist_id, $plugin_cookies, 0, $this->lazy_limit);
        }
        if ($movie === null) {
            return null;
        }

        $sel_id = isset($media_url->serie_id) ?
            $media_url->serie_id : null;
//        hd_print("get_vod_info");
        /////////////////////////////////
        /////////////////////////////////
        /////////////////////////////////
        /////////////////////////////////
        /////////////////////////////////

//        $this->fetch_genre_list();
        $this->fetch_genre_tree();

        /////////////////////////////////
        /////////////////////////////////
        /////////////////////////////////
        /////////////////////////////////
        /////////////////////////////////
        if (!isset($this->toplist)) {
            $this->fetch_topmovie_list(null);
        }

        $i = 0;
        $no_top = 1;
        foreach ($this->toplist as $t) {
            if ($t == $media_url->serial_id) {
                $no_top = 0;
                break;
            }
            $i++;
            if ($i >= 3) {
                break;
            }
        }

        if ($no_top) {
            if (isset($plugin_cookies->prodhist)) {
                $prodhist = json_decode($plugin_cookies->prodhist, true);
            } else {
                $prodhist = array();
            }

            foreach ($prodhist as $k => $val) {
                if (($val['type'] == 2) && ($val['serial_id'] == $media_url->serial_id)) {
                    unset($prodhist[$k]);
                }
            }

            $len = array_unshift($prodhist, array(
                'type' => 2,
                'serial_id' => $media_url->serial_id));

            if ($len > 8) {
                array_pop($prodhist);
            }
            $plugin_cookies->prodhist = json_encode($prodhist);
        }
        return $movie->get_vod_info($sel_id, 3000);
    }

    public function get_folder_view(MediaURL $media_url, &$plugin_cookies)
    {

//        hd_print("SETTING BACKGROUND = ".$this->BACKGROUND);

        if (empty($media_url->serieslist_id) && !empty($media_url->serial_id)) {
            $seasons = $this->getCountSeasons($media_url->serial_id);
            if ( $seasons< 2) $media_url->serieslist_id = $media_url->serial_id . ";".$seasons;

        }
        if (isset($media_url->season_id)) {
            $movie = $this->get_loaded_series($media_url->serial_id, $media_url->season_id, $plugin_cookies);
            if ($movie === null) {
                return null;
            }



//            hd_print("GET VIDEO URL!!!!!!!!!!!!!!!!!!!!!!!!!!");


            $left_button_caption = $this->get_movie_left_button_caption(
                $media_url, $plugin_cookies);
            $left_button_action = (count($movie->series_list) > 1) ?
                $this->get_movie_left_button_action($media_url, $plugin_cookies) :
                array
                (
                    GuiAction::handler_string_id => PLUGIN_TV_PLAY_ACTION_ID,
                    GuiAction::data =>
                        array
                        (
                            PluginOpenFolderActionData::media_url => $movie->series_list[0]->playback_url
                        )
                );

            $this->vod->get_movie_left_button_action(
                $media_url, $plugin_cookies);

            $has_right_button = $this->vod->is_favorites_supported();
            $right_button_caption = null;
            $right_button_action = null;

            if ($has_right_button)
            {
                $this->vod->ensure_favorites_loaded($plugin_cookies);

                $is_favorite = $this->vod->is_favorite_movie_id($movie->id);
                $right_button_caption = $is_favorite ?
                'Удалить из избранного' : 'Добавить в избранное';
                $right_button_action = UserInputHandlerRegistry::create_action(
                    $this, 'favorites',
                    array('movie_id' => $movie->id));
            }

            $listurl = MediaURL::encode(
                array(
                    'screen_id' => $this->id,
                    'serial_id' => $media_url->serial_id,
                    'serieslist_id' => $media_url->season_id,
                ));

            $movie_folder_view = array
            (
                PluginMovieFolderView::movie => $movie->get_movie_array(),
                PluginMovieFolderView::left_button_caption => $left_button_caption,
                PluginMovieFolderView::left_button_action => $left_button_action,
                PluginMovieFolderView::has_right_button => $has_right_button,
                PluginMovieFolderView::right_button_caption => $right_button_caption,
                PluginMovieFolderView::right_button_action => $right_button_action,

                PluginMovieFolderView::params => array
                (
                    PluginFolderViewParams::background_url => $this->BACKGROUND,//I24hConfig::BG_PIC,
                ),
                PluginMovieFolderView::has_multiple_series => (count($movie->series_list) > 1),
                PluginMovieFolderView::series_media_url => $listurl,
                PluginRegularFolderView::view_params => array
                (
                    ViewParams::num_cols => 1,
                    ViewParams::num_rows => 10,
                    ViewParams::paint_details => true,
                    ViewParams::paint_item_info_in_details => true,
                    ViewParams::zoom_detailed_icon => true,
                    ViewParams::detailed_icon_scale_factor => 0.5,
                    ViewParams::item_detailed_info_text_color => 10,
                    ViewParams::item_detailed_info_auto_line_break => true
                ),

            );

            return array
            (
                PluginFolderView::multiple_views_supported => false,
                PluginFolderView::archive => null,
                PluginFolderView::view_kind => PLUGIN_FOLDER_VIEW_MOVIE,
                PluginFolderView::data => $movie_folder_view,
            );
        } else if (isset($media_url->serieslist_id)) {
            $folder_view =
                array
                (
                    PluginRegularFolderView::view_params => array
                    (
                        ViewParams::num_cols => 1,
                        ViewParams::num_rows => 4,
                        ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                        ViewParams::background_width => 1920,
                        ViewParams::background_height => 1080,
                        ViewParams::background_order => 'before_all',

                    ),
                    PluginRegularFolderView::base_view_item_params => array
                    (
                        ViewItemParams::item_layout => HALIGN_LEFT,
                        ViewItemParams::icon_valign => VALIGN_CENTER,
                        ViewItemParams::icon_dx => 10,
                        ViewItemParams::icon_dy => -5,
                        ViewItemParams::icon_sel_dx => 10,
                        ViewItemParams::icon_sel_dy => -5,
                        ViewItemParams::item_caption_dx => 300,
                        ViewItemParams::item_caption_dy => -30,
                        ViewItemParams::item_caption_sel_dy => -30,
                        ViewItemParams::item_caption_wrap_enabled => true,
                        ViewItemParams::icon_scale_factor => 0.8,
                        ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai',
                    ),

                    PluginRegularFolderView::not_loaded_view_item_params => array(),

                );
        } else if (isset($media_url->serial_id)) {

            $folder_view = array
            (
                PluginRegularFolderView::async_icon_loading => true,

                PluginRegularFolderView::view_params => array
                (
                    ViewParams::num_cols => 1,
                    ViewParams::num_rows => 6,
                    ViewParams::paint_details => true,
                    ViewParams::detailed_icon_scale_factor => 1.5,
                    ViewParams::item_detailed_info_rel_y => 315,
                    ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                    ViewParams::background_width => 1920,
                    ViewParams::background_height => 1080,
                    ViewParams::background_order => 'before_all',
                    ViewParams::item_detailed_info_auto_line_break => true,
                ),

                PluginRegularFolderView::base_view_item_params => array
                (
                    ViewItemParams::item_paint_icon => false,
                    ViewItemParams::item_layout => HALIGN_LEFT,
                    ViewItemParams::icon_valign => VALIGN_CENTER,
                    ViewItemParams::icon_dx => 15,
                    ViewItemParams::icon_dy => -5,
                    ViewItemParams::item_caption_dx => 70,
                    ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                    ViewItemParams::item_caption_width => 1550,
                    ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai',
                    ViewItemParams::item_detailed_icon_path => ''

                ),

                PluginRegularFolderView::not_loaded_view_item_params => array(),
            );
        } else if (isset($media_url->genre_id)) {

            $t = $this->get_ganre_by_id($media_url->genre_id);

            if ($t["has_child"]) {
                # Жанр есть и есть поджанры

//                hd_print("Жанр есть и есть поджанры");
//                hd_print("Template = ".$t["template"]);
//                hd_print("Image = ".$t["img"]);

                switch ($t["template"]){
                    case 'grid_w':
                        $folder_view =
                            array
                            (
                                PluginRegularFolderView::async_icon_loading => true,

                                PluginRegularFolderView::view_params => array
                                (
                                    ViewParams::num_cols => 2,
                                    ViewParams::num_rows => 8,
                                    ViewParams::paint_details => false,
                                    ViewParams::optimize_full_screen_background => true,
                                    ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                    ViewParams::background_width => 1920,
                                    ViewParams::background_height => 1080,
                                    ViewParams::background_order => 'before_all'
                                ),

                                PluginRegularFolderView::base_view_item_params => array
                                (

                                    ViewItemParams::item_paint_icon => true,
                                    ViewItemParams::item_layout => HALIGN_LEFT,
                                    ViewItemParams::icon_valign => VALIGN_CENTER,
                                    ViewItemParams::icon_dx => 15,
                                    ViewItemParams::icon_dy => -5,
                                    ViewItemParams::item_caption_dx => 70,
                                    ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                                    ViewItemParams::item_caption_width => 1550,
                                    ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'
                                ),

                                PluginRegularFolderView::not_loaded_view_item_params => array(),
                            );
                        break;
                    case 'grid_promo_w':
                        $folder_view =
                            array
                            (
                                PluginRegularFolderView::async_icon_loading => true,

                                PluginRegularFolderView::view_params => array
                                (
                                    ViewParams::num_cols => 2,
                                    ViewParams::num_rows => 8,
                                    ViewParams::paint_details => false,
                                    ViewParams::optimize_full_screen_background => true,
                                    ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                    ViewParams::background_width => 1920,
                                    ViewParams::background_height => 1080,
                                    ViewParams::background_order => 'before_all'
                                ),

                                PluginRegularFolderView::base_view_item_params => array
                                (

                                    ViewItemParams::item_paint_icon => true,
                                    ViewItemParams::item_layout => HALIGN_LEFT,
                                    ViewItemParams::icon_valign => VALIGN_CENTER,
                                    ViewItemParams::icon_dx => 15,
                                    ViewItemParams::icon_dy => -5,
                                    ViewItemParams::item_caption_dx => 70,
                                    ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                                    ViewItemParams::item_caption_width => 1550,
                                    ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'
                                ),

                                PluginRegularFolderView::not_loaded_view_item_params => array(),
                            );
                        break;
                    case 'subfilters':

                        $folder_view = array
                        (
                            PluginRegularFolderView::async_icon_loading => true,

                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 4,
                                ViewParams::num_rows => 1,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 370,
                                ViewParams::sandwich_height => 600,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => true,
                                ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                ViewParams::background_width => 1920,
                                ViewParams::background_height => 1080,
                                ViewParams::background_order => 'before_all'
                            ),

                            PluginRegularFolderView::base_view_item_params => array
                            (
                                ViewItemParams::item_paint_icon => true,
                                ViewItemParams::item_layout => HALIGN_CENTER,
                                ViewItemParams::icon_valign => VALIGN_TOP,
                                ViewItemParams::item_paint_caption => true,
                                ViewItemParams::icon_scale_factor => 1.0,
                                ViewItemParams::item_caption_wrap_enabled => true,
                                ViewItemParams::item_caption_dy => -20,
                                ViewItemParams::item_caption_sel_dy => -20,
                                ViewItemParams::icon_dy => 7,
                                ViewItemParams::icon_sel_dy => 7,
                            ),

                            PluginRegularFolderView::not_loaded_view_item_params => array
                            (
                                ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                                ViewItemParams::item_detailed_icon_path => 'missing://',
                            ),
                        );



                        break;
                    case 'grid_v':

//                        hd_print(" Тута !!!!!!!!!!!!!!!! grid_v ");

                        $folder_view =
                            array
                            (
                                PluginRegularFolderView::async_icon_loading => true,

                                PluginRegularFolderView::view_params => array
                                (
                                    ViewParams::num_cols => 2,
                                    ViewParams::num_rows => 8,
                                    ViewParams::paint_details => false,
                                    ViewParams::optimize_full_screen_background => true,
                                    ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                    ViewParams::background_width => 1920,
                                    ViewParams::background_height => 1080,
                                    ViewParams::background_order => 'before_all'
                                ),

                                PluginRegularFolderView::base_view_item_params => array
                                (

                                    ViewItemParams::item_paint_icon => true,
                                    ViewItemParams::item_layout => HALIGN_LEFT,
                                    ViewItemParams::icon_valign => VALIGN_CENTER,
                                    ViewItemParams::icon_dx => 15,
                                    ViewItemParams::icon_dy => -5,
                                    ViewItemParams::item_caption_dx => 70,
                                    ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                                    ViewItemParams::item_caption_width => 1550,
                                    ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'
                                ),

                                PluginRegularFolderView::not_loaded_view_item_params => array(),
                            );
                        break;
                    case 'grid_promo_v':

                        $folder_view =
                            array
                            (
                                PluginRegularFolderView::async_icon_loading => true,

                                PluginRegularFolderView::view_params => array
                                (
                                    ViewParams::num_cols => 2,
                                    ViewParams::num_rows => 8,
                                    ViewParams::paint_details => false,
                                    ViewParams::optimize_full_screen_background => true,
                                    ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                    ViewParams::background_width => 1920,
                                    ViewParams::background_height => 1080,
                                    ViewParams::background_order => 'before_all'
                                ),

                                PluginRegularFolderView::base_view_item_params => array
                                (

                                    ViewItemParams::item_paint_icon => true,
                                    ViewItemParams::item_layout => HALIGN_LEFT,
                                    ViewItemParams::icon_valign => VALIGN_CENTER,
                                    ViewItemParams::icon_dx => 15,
                                    ViewItemParams::icon_dy => -5,
                                    ViewItemParams::item_caption_dx => 70,
                                    ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                                    ViewItemParams::item_caption_width => 1550,
                                    ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'
                                ),

                                PluginRegularFolderView::not_loaded_view_item_params => array(),
                            );

                        break;
                }

            }else{

                $t = $this->get_ganre_by_id($media_url->genre_id);
//                hd_print("Жанр задан, поджанров нет");
//                hd_print("Template = ".$t["template"]);
//                hd_print("Image = ".$t["img"]);

                # Жанр задан, поджанров нет

                switch ($t["template"]){
                    case 'grid_w':
                    $folder_view = array
                    (
                        PluginRegularFolderView::async_icon_loading => true,

                        PluginRegularFolderView::view_params => array
                        (
                            ViewParams::num_cols => 4,
                            ViewParams::num_rows => 2,
                            ViewParams::paint_details => false,
                            ViewParams::orientation => 'horizontal',
                            ViewParams::sandwich_width => 380,
                            ViewParams::sandwich_height => 240,
                            ViewParams::sandwich_icon_upscale_enabled => true,
                            ViewParams::sandwich_icon_keep_aspect_ratio => false,
                            ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                            ViewParams::background_width => 1920,
                            ViewParams::background_height => 1080,
                            ViewParams::background_order => 'before_all'
                        ),

                        PluginRegularFolderView::base_view_item_params => array
                        (
                            ViewItemParams::item_paint_icon => true,
                            ViewItemParams::item_layout => HALIGN_CENTER,
                            ViewItemParams::icon_valign => VALIGN_TOP,
                            ViewItemParams::item_paint_caption => true,
                            ViewItemParams::icon_scale_factor => 1.0,
                            ViewItemParams::item_caption_wrap_enabled => true,
                            ViewItemParams::item_caption_dy => -40,
                            ViewItemParams::item_caption_sel_dy => -40,
                            ViewItemParams::icon_dy => 7,
                            ViewItemParams::icon_sel_dy => 7,
                        ),

                        PluginRegularFolderView::not_loaded_view_item_params => array
                        (
                            ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                            ViewItemParams::item_detailed_icon_path => 'missing://',
                        ),
                    );
                break;
                    case 'grid_promo_w':
                    $folder_view = array
                    (
                        PluginRegularFolderView::async_icon_loading => true,

                        PluginRegularFolderView::view_params => array
                        (
                            ViewParams::num_cols => 4,
                            ViewParams::num_rows => 2,
                            ViewParams::paint_details => false,
                            ViewParams::orientation => 'horizontal',
                            ViewParams::sandwich_width => 380,
                            ViewParams::sandwich_height => 240,
                            ViewParams::sandwich_icon_upscale_enabled => true,
                            ViewParams::sandwich_icon_keep_aspect_ratio => false,
                            ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                            ViewParams::background_width => 1920,
                            ViewParams::background_height => 1080,
                            ViewParams::background_order => 'before_all'
                        ),

                        PluginRegularFolderView::base_view_item_params => array
                        (
                            ViewItemParams::item_paint_icon => true,
                            ViewItemParams::item_layout => HALIGN_CENTER,
                            ViewItemParams::icon_valign => VALIGN_TOP,
                            ViewItemParams::item_paint_caption => true,
                            ViewItemParams::icon_scale_factor => 1.0,
                            ViewItemParams::item_caption_wrap_enabled => true,
                            ViewItemParams::item_caption_dy => -40,
                            ViewItemParams::item_caption_sel_dy => -40,
                            ViewItemParams::icon_dy => 7,
                            ViewItemParams::icon_sel_dy => 7,
                        ),

                        PluginRegularFolderView::not_loaded_view_item_params => array
                        (
                            ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                            ViewItemParams::item_detailed_icon_path => 'missing://',
                        ),
                    );
                break;
                    case 'grid_v':
                        $folder_view = array
                        (
                            PluginRegularFolderView::async_icon_loading => true,

                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 5,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 180,
                                ViewParams::sandwich_height => 240,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                ViewParams::background_width => 1920,
                                ViewParams::background_height => 1080,
                                ViewParams::background_order => 'before_all'
                            ),

                            PluginRegularFolderView::base_view_item_params => array
                            (
                                ViewItemParams::item_paint_icon => true,
                                ViewItemParams::item_layout => HALIGN_CENTER,
                                ViewItemParams::icon_valign => VALIGN_TOP,
                                ViewItemParams::item_paint_caption => true,
                                ViewItemParams::icon_scale_factor => 1.0,
                                ViewItemParams::item_caption_wrap_enabled => true,
                                ViewItemParams::item_caption_dy => -40,
                                ViewItemParams::item_caption_sel_dy => -40,
                                ViewItemParams::icon_dy => 7,
                                ViewItemParams::icon_sel_dy => 7,
                            ),

                            PluginRegularFolderView::not_loaded_view_item_params => array
                            (
                                ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                                ViewItemParams::item_detailed_icon_path => 'missing://',
                            ),
                        );
                    break;
                    case 'grid_promo_v':
                        $folder_view = array
                        (
                            PluginRegularFolderView::async_icon_loading => true,

                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 5,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 180,
                                ViewParams::sandwich_height => 240,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                ViewParams::background_width => 1920,
                                ViewParams::background_height => 1080,
                                ViewParams::background_order => 'before_all'
                            ),

                            PluginRegularFolderView::base_view_item_params => array
                            (
                                ViewItemParams::item_paint_icon => true,
                                ViewItemParams::item_layout => HALIGN_CENTER,
                                ViewItemParams::icon_valign => VALIGN_TOP,
                                ViewItemParams::item_paint_caption => true,
                                ViewItemParams::icon_scale_factor => 1.0,
                                ViewItemParams::item_caption_wrap_enabled => true,
                                ViewItemParams::item_caption_dy => -40,
                                ViewItemParams::item_caption_sel_dy => -40,
                                ViewItemParams::icon_dy => 7,
                                ViewItemParams::icon_sel_dy => 7,
                            ),

                            PluginRegularFolderView::not_loaded_view_item_params => array
                            (
                                ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                                ViewItemParams::item_detailed_icon_path => 'missing://',
                            ),
                        );
                    break;
                }


            }
        } else {

            $this->fetch_genre_tree();

//            hd_print("Жанры не заданы вообще");
//
//            hd_print("Template = ".$this->TEMPLATE);
//            hd_print("Image = ".$this->BACKGROUND);
// subfilters grid_w grid_v

            switch ($this->TEMPLATE){
                case 'grid_w':
                    $folder_view =
                        array
                        (
                            PluginRegularFolderView::async_icon_loading => true,

                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 2,
                                ViewParams::num_rows => 8,
                                ViewParams::paint_details => false,
                                ViewParams::optimize_full_screen_background => true,
                                ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                                ViewParams::background_width => 1920,
                                ViewParams::background_height => 1080,
                                ViewParams::background_order => 'before_all'
                            ),

                            PluginRegularFolderView::base_view_item_params => array
                            (

                                ViewItemParams::item_paint_icon => true,
                                ViewItemParams::item_layout => HALIGN_LEFT,
                                ViewItemParams::icon_valign => VALIGN_CENTER,
                                ViewItemParams::icon_dx => 15,
                                ViewItemParams::icon_dy => -5,
                                ViewItemParams::item_caption_dx => 70,
                                ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                                ViewItemParams::item_caption_width => 1550,
                                ViewItemParams::icon_path => 'gui_skin://small_icons/folder.aai'
                            ),

                            PluginRegularFolderView::not_loaded_view_item_params => array(),
                        );
                    break;
                case 'subfilters':

                    $folder_view = array
                    (
                        PluginRegularFolderView::async_icon_loading => true,

                        PluginRegularFolderView::view_params => array
                        (
                            ViewParams::num_cols => 4,
                            ViewParams::num_rows => 1,
                            ViewParams::paint_details => false,
                            ViewParams::orientation => 'horizontal',
                            ViewParams::sandwich_width => 370,
                            ViewParams::sandwich_height => 600,
                            ViewParams::sandwich_icon_upscale_enabled => true,
                            ViewParams::sandwich_icon_keep_aspect_ratio => true,
                            ViewParams::background_path => $this->BACKGROUND,//I24hConfig::BG_PIC,
                            ViewParams::background_width => 1920,
                            ViewParams::background_height => 1080,
                            ViewParams::background_order => 'before_all'
                        ),

                        PluginRegularFolderView::base_view_item_params => array
                        (
                            ViewItemParams::item_paint_icon => true,
                            ViewItemParams::item_layout => HALIGN_CENTER,
                            ViewItemParams::icon_valign => VALIGN_TOP,
                            ViewItemParams::item_paint_caption => true,
                            ViewItemParams::icon_scale_factor => 1.0,
                            ViewItemParams::item_caption_wrap_enabled => true,
                            ViewItemParams::item_caption_dy => -20,
                            ViewItemParams::item_caption_sel_dy => -20,
                            ViewItemParams::icon_dy => 7,
                            ViewItemParams::icon_sel_dy => 7,
                        ),

                        PluginRegularFolderView::not_loaded_view_item_params => array
                        (
                            ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                            ViewItemParams::item_detailed_icon_path => 'missing://',
                        ),
                    );



                    break;
                case 'grid_v':
                    break;
            }
        }

        $folder_view[PluginRegularFolderView::actions] =
            $this->get_action_map($media_url, $plugin_cookies);

        $folder_view[PluginRegularFolderView::initial_range] =
            $this->get_folder_range($media_url, 0, $plugin_cookies);

        $archive = $this->get_archive($media_url);
        $archive_def = is_null($archive) ? null :
            $archive->get_archive_def();

        return array
        (
            PluginFolderView::multiple_views_supported => 0,
            PluginFolderView::archive => $archive_def,
            PluginFolderView::view_kind => PLUGIN_FOLDER_VIEW_REGULAR,
            PluginFolderView::data => $folder_view
        );
    }


    public function getCountSeason($season_id)
    {
        $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST,
            $season_id, $this->session->get_token()));
        if (is_null($doc))
            throw new Exception('Can not fetch topmovie list');
        $xml = simplexml_load_string($doc);

        if ($xml === false) {
            hd_print("Error: can not parse XML document.");
            hd_print("XML-text: $doc.");
            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');
        }

        foreach ($xml->children() as $c) {
            return strval($c->season);
        }


    }

    public function getCountSeasons($season_id)
    {
        $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST,
            $season_id, $this->session->get_token()));
        if (is_null($doc))
            throw new Exception('Can not fetch topmovie list');
        $xml = simplexml_load_string($doc);

        if ($xml === false) {
            hd_print("Error: can not parse XML document.");
            hd_print("XML-text: $doc.");
            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');
        }
        $seasons = 0;
        foreach ($xml->children() as $c) {
            if (intval($c->season)>$seasons){$seasons = intval($c->season);};
        }
        return $seasons;
    }

    public function getCountSeries($serial_id,$season){
        $doc = HD::http_get_document(sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST,
            $serial_id, $this->session->get_token()));
        if (is_null($doc))
            throw new Exception('Can not fetch topmovie list');
        $xml = simplexml_load_string($doc);

        if ($xml === false) {
            hd_print("Error: can not parse XML document.");
            hd_print("XML-text: $doc.");
            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');
        }
        $series = 0;
        foreach ($xml->children() as $c) {
            if (intval($c->season) == $season) {
                if (intval($c->series) > $series) {
                    $series = intval($c->series);
                };
            }
        }
        return $series;
    }

    public function handle_user_input(&$user_input, &$plugin_cookies)
    {

      hd_print("handle_user_input");
      hd_print(print_r($user_input,true));


      if ($user_input->control_id == 'play_video') {
            $this->is_user_subcribers();
            if ($this->allow_view) {
                $curr_medial_url = MediaURL::decode($user_input->selected_media_url);


                $need_req_pass = empty($plugin_cookies->need_password_sextv)?'no':$plugin_cookies->need_password_sextv;

                if ($this->serials[$curr_medial_url->serial_id]['age']<18) {
                    return ActionFactory::vod_play();
                }else{
                    if ($need_req_pass=='yes') {
                        $defs = array();
                        ControlFactory::add_text_field($defs, $this, null, 'password', 'Пароль:', '', true, true, false, true, 400);
                        ControlFactory::add_vgap($defs, 40);
                        ControlFactory::add_close_dialog_and_apply_button($defs, $this, array('button_caption_centered' => true), 'apply_code', 'OK', 300);
                        ControlFactory::add_button_close($defs, $this, array('button_caption_centered' => true), 'cancel', null, '    Отмена', 300);
                        return ActionFactory::show_dialog('Введите пароль родительского контроля', $defs);
                    }else{
                        return ActionFactory::vod_play();
                    }
                }
            } else {
                $defs = array();
                $tarifs = implode(", ", $this->allow_in_packets);

                ControlFactory::add_label($defs, null, 'К сожалению, у Вас нет доступа к "'.$this->name.'"!');
                ControlFactory::add_vgap($defs, 40);
                ControlFactory::add_label($defs, null, 'Для доступа к "'.$this->name.'" зайдите в личный кабинет');
                ControlFactory::add_label($defs, null, 'и выберите один из следующих тарифов:');
                ControlFactory::add_vgap($defs, 40);
                ControlFactory::add_label($defs, null, $tarifs);
                ControlFactory::add_vgap($defs, 40);
                ControlFactory::add_label($defs, null, 'Для выбора тарифа, нажмите кнопку "Подключить".');
                ControlFactory::add_vgap($defs, 40);
                ControlFactory::add_button_close($defs, $this, array('button_caption_centered'=>true), 'to_tariffs', null, ' Подключить', 300);
                ControlFactory::add_button_close($defs, $this, array('button_caption_centered'=>true), 'cancel', null, '    Отмена', 300);

                return ActionFactory::show_dialog('Внимание!', $defs);
            }
        }else if ($user_input->control_id == 'to_tariffs'){
            return ActionFactory::open_folder(I24hPrivateScreen::get_media_url_str(''),'Управление тарифами');
        }else if ($user_input->control_id == 'apply_code'){
            if ($user_input->password === $this->session->get_parental_code()){
                return ActionFactory::vod_play();
            }else{
                $defs = array();
                ControlFactory::add_button_close($defs, $this, array('button_caption_centered'=>true), 'cancel', null, 'OK',300);
                return ActionFactory::show_dialog('Введен неверный пароль родительского контроля!', $defs);
            }

        }
    }
}

?>
