<?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
{
    private $topcats;
    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 static function get_media_url_str($category_id, $id)
    {
        return MediaURL::encode(
            array
            (
                'screen_id' => $id,
                'category_id' => $category_id,
            ));
    }

    public function __construct($session, $screen_id, $filter_id, $source_id, $name, $is_need_label, $background)
    {
        parent::__construct($screen_id, array());
        $this->session = $session;
        $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 = empty($is_need_label) ? false : $is_need_label;
        $this->BACKGROUND = $background;
        UserInputHandlerRegistry::get_instance()->register_handler($this);
    }

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

        if (!empty($media_url->image) and $media_url->image == 'image') {
            $show_image =
                UserInputHandlerRegistry::create_action(
                    $this, 'show_image');
            return array
            (
                GUI_EVENT_KEY_ENTER => $show_image,
                GUI_EVENT_KEY_PLAY => $show_image
            );

        }
        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)
    {
        $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)) {

            if (I24hConfig::DEBUG) hd_print('Выводим список серий');

            $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++;
                if (I24hConfig::DEBUG) hd_print("Иконки серий " . $s->icon);
                $img = $this->is_need_label ? ($s->icon . "&video_label=true&id=" . $media_url->serial_id) : ($s->icon);
                $items[] = array
                (
                    PluginRegularFolderItem::media_url => $s_mediaurl,
                    PluginRegularFolderItem::caption => $s->name,
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => $img,
                    )
                );
                $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)) {
            // Вывод списка сезонов/серий/запуск видео
            $seasons = $this->getCountSeasons($media_url->serial_id);
            if ($seasons > 1) {
                // Выводим список сезонов, их много
                if (I24hConfig::DEBUG) hd_print("Выводим список сезонов, их много");
                $count_video = 0;
                $items = array();
                $serial = $this->fetch_serial($media_url->serial_id);

                if (I24hConfig::DEBUG) hd_print(print_r($serial, true));

                $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=180&video_label=true&id=" . $serial["id"] : "?w=320&h=180");
                        $items[] = array
                        (
                            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;
                }
                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++;
                }
                return HD::create_regular_folder_range($items, $from_ndx, $count_video, false);
            }
        } else if (isset($media_url->genre_id)) {

            $t = $this->get_ganre_by_id($media_url->genre_id);
            if ($t["has_child"]) {
                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'
                        )
                    );
                }
                return HD::create_regular_folder_range(
                    $items, 0, count($items), false);

            } else {
                # Жанр задан, нет деток, выводим сериалы
                if (I24hConfig::DEBUG) 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 =>
                            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']
                        )
                    );
                    $count_video++;
                }
            }


        } else {
            # Жанр не задан, выводим список жанров верхнего уровня
            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'
                            )
                        );
                    }
                    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'
                            )
                        );
                    }
                    break;
                case "promo":
                    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_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;

            }
            return HD::create_regular_folder_range(
                $items, 0, count($items), false);

        }
        $more = false;
        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();

        $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"] == 'program') {


                $mediaurl = MediaURL::encode(
                    array(
                        'screen_id' => "vod_movie",
                        'movie_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"],
                                'archive_tm' => $s["timestamp"],
                                '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']),
                        ViewItemParams::item_detailed_icon_path => strval($s['img']),
                    )
                );
            } else if ($s["type"] == 'image') {
                $mediaurl = MediaURL::encode(
                    array(
                        'screen_id' => $this->id,
                        'image' => 'image',
                        'img_src' => $s['img_src'],
                        'name' => $s['name']
                    ));

                $show_image =
                    UserInputHandlerRegistry::create_action(
                        $this, 'show_image');

                $items[] = array
                (
                    PluginRegularFolderItem::media_url => $mediaurl,

                    PluginRegularFolderView::actions => array
                    (
                        GUI_EVENT_KEY_ENTER => $show_image,
                        GUI_EVENT_KEY_PLAY => $show_image,
                    ),
                    PluginRegularFolderItem::caption => $s['name'],
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => strval($s['img'])
                    )
                );
            } else if ($s["type"] == 'filter') {

                $items[] = array
                (
                    PluginRegularFolderItem::media_url => I24hVodSeriesListScreen::get_media_url_str($s['id'], $s['id']),
                    PluginRegularFolderItem::caption => $s['name'],
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => strval($s['img'])
                    )
                );

            }
            $i++;
            if ($i > $count) {
                break;
            }

        }
        return $items;
    }

    public function make_single_item($serial_id)
    {
        $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=180";
        } else {
            $img = strval($s['img']) . "?w=320&h=180&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) {

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

            foreach ($doc as $c) {

                if (strval($c->destination->type) == 'program') {
                    $banner = $c->banner . "?w=320&h=180";

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

                } else if (strval($c->destination->type) == 'video') {

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

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

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

                } else if (strval($c->destination->type) == 'channel') {

                    $banner = $c->banner . "?w=320&h=180";
                    if (empty($c->destination->timestamp)) {
                        $timestamp = 0;
                    } else {
                        $timestamp = strval($c->destination->timestamp);
                    }
                    $this->serials[intval($c->destination->id)] = array(
                        'id' => intval($c->destination->id),
                        'type' => 'channel',
                        'name' => strval($c->title),
                        'descr' => strval($c->description),
                        'img' => $banner,
                        'timestamp' => $timestamp
                    );
                    $this->toplist[] = strval($c->destination->id);

                } else if (strval($c->destination->type) == 'image') {

                    $banner = $c->banner . "?w=320&h=180";
                    $this->serials[strval($c->destination->id)] = array(
                        'id' => strval($c->destination->id),
                        'type' => 'image',
                        'name' => strval($c->title),
                        'descr' => strval($c->description),
                        'img' => $banner,
                        'img_src' => strval($c->destination->src)
                    );
                    $this->toplist[] = strval($c->destination->id);

                } else if (strval($c->destination->type) == 'filter') {

                    $banner = $c->banner . "?w=320&h=180";
                    $this->serials[strval($c->destination->id)] = array(
                        'id' => strval($c->destination->id),
                        'type' => 'filter',
                        'name' => strval($c->title),
                        'descr' => strval($c->description),
                        'img' => $banner
                    );
                    $this->toplist[] = strval($c->destination->id);
                }
            }

        } else {
            if (I24hConfig::DEBUG) hd_print("fetch_topmovie_list");
            $this->genres[$genre_id]['serials'] = array();
            if (!isset($this->genres)) $this->fetch_genre_tree();

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

            foreach ($doc as $c) {
                $poster = "";
                $cover = "";
                foreach ($c->img as $i) {
                    if (strval($i->type) == 'cover') {
                        $cover = strval($i->src);
                    } else {
                        $poster = strval($i->src);
                    }
                }
                $image = empty($cover) ? $poster : $cover;
                $image .= "?w=200&h=300&crop=true";
                if (I24hConfig::DEBUG) hd_print(strval($c->title) . " " . $image);
                $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' => $image,
                    'seasons' => array()
                );
                $this->genres[$genre_id]['serials'][] = $this->serials[strval($c->id)];
            }
        }
    }


    private function fetch_genre_tree()
    {
        $this->genres_tree = array();

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

        foreach ($doc as $m) {
            if ($m->id == $this->filter_id) {
                $this->TEMPLATE = strval($m->template);
                foreach ($m->filters 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) > 0 ? 1 : 0
                    );
                    $count = 0;
                    foreach ($l->filters as $c) {
                        if (I24hConfig::DEBUG) hd_print(strval($c->name) . " " . strval($c->image));
                        $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
                        );
                    }
                }
            }
        }

        if (count($this->genres_tree) == 0){
            if (I24hConfig::DEBUG) hd_print("genres_tree is empty!!!");
                foreach ($doc as $first_level) {
                    foreach ($first_level->filters as $second_level) {
                        if ($second_level->id == $this->filter_id) {

                            $this->TEMPLATE = strval($second_level->template);
                            foreach ($second_level->filters 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) > 0 ? 1 : 0
                                );
                                $count = 0;
                                foreach ($l->filters as $c) {
                                    if (I24hConfig::DEBUG) hd_print(strval($c->name) . " " . strval($c->image));
                                    $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_series_list($season_id, $from_ndx, $lazy_limit)
    {
        $series = array();
        $serils_seasons = preg_split('/;/', strval($season_id));

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

        if (count($doc) > 0) {
            foreach ($doc as $c) {
                if ($c->season == $serils_seasons[1]) {
                    $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=180",
                    );
                }
            }
        } else {

            $url = sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIAL, $serils_seasons[0], $this->session->get_token());

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

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

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

        }
        return $series;
    }

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

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

            $countries = array();
            foreach ($doc->countries as $c){
                $countries[] = $c->name;
            }

            $this->serials[strval($doc->id)] = array(
                'id' => strval($doc->id),
                'name' => strval($doc->title),
                'original' => strval($doc->original),
                'rating_imdb' => strval($doc->rating_imdb),
                'rating_kinopoisk' => strval($doc->rating_kinopoisk),
                'source_id' => strval($doc->source->id),
                'age' => strval($doc->age),
                'year' => strval($doc->year),
                'descr' => strval($doc->description),
                'countries' => strval(substr(implode(", ", $countries), 0)),
                'img' => $img . "?w=147&h=220&crop=true",
                'seasons' => array()
            );

            if (!empty($doc->episodes)) {
                foreach ($doc->episodes as $ep) {
                    if (!isset($ep->season)) {
                        continue;
                    }
                    $seasons[strval($doc->id) . ";" . strval($ep->season)] = strval($ep->list_title);
                }
            } else {
                $seasons[strval($doc->id) . ";0"] = strval($doc->title);
            }

            foreach ($seasons as $k => $v) {
                $arr = preg_split("/;/", $k);
                if ($arr[1] > 0) {
                    $this->serials[strval($doc->id)]['seasons'][strval($k)] = array(
                        'id' => strval($k),
                        'name' => 'Сезон ' . $arr[1],
                        'year' => strval($doc->year),
                        'descr' => strval($doc->description),
                        'img' => $img . "?w=200&h=300&crop=true",
                    );
                } else {
                    $this->serials[strval($doc->id)]['seasons'][strval($k)] = array(
                        'id' => strval($k),
                        'name' => strval($doc->title),
                        'year' => strval($doc->year),
                        'descr' => strval($doc->description),
                        'img' => $img . "?w=200&h=300&crop=true",
                    );

                }
            }

            return $this->serials[strval($doc->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)
    {

        if (I24hConfig::DEBUG) 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);

        if (I24hConfig::DEBUG) hd_print("---------------------------");
        if (I24hConfig::DEBUG) hd_print(print_r($serial, true));
        if (I24hConfig::DEBUG) 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'],
            $serial['countries'],
            ''
        );

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

        $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;
                if (($movie->rate_mpaa >= 18) and ($need_req_pass == 'yes')) {
                    $movie = $this->get_loaded_series(0, "0;0", $plugin_cookies, 0, $this->lazy_limit);
                }
            } else {
                $movie = $this->get_loaded_series(0, "0;0", $plugin_cookies, 0, $this->lazy_limit);
            }
        } 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;
        $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)
    {

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

            $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,
                ),
                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)) {
            hd_print("media_url->serieslist_id");
            $folder_view =
                array
                (
                    PluginRegularFolderView::view_params => array
                    (
                        ViewParams::num_cols => 1,
                        ViewParams::num_rows => 4,
                        ViewParams::background_path => $this->BACKGROUND,
                        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 => 6,
                        ViewItemParams::icon_dy => -6,
                        ViewItemParams::icon_width => 383,
                        ViewItemParams::icon_height => 215,
                        ViewItemParams::icon_keep_aspect_ratio => false,
                        ViewItemParams::item_caption_dx => 360,
                        ViewItemParams::item_caption_dy => 0,
                        ViewItemParams::item_caption_sel_dy => 0,
                        ViewItemParams::item_caption_wrap_enabled => false,
                        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)) {
            hd_print("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,
                    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"]) {
                # Жанр есть и есть поджанры
                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,
                                    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 => 0,
                                    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,
                                    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 => 540,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => true,
                                ViewParams::background_path => $this->BACKGROUND,
                                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("1");
                        $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,
                                    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 => 0,
                                    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,
                                    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);
                if (empty($t["template"])) {
                    $t["template"] = "grid_w";
                }
                # Жанр задан, поджанров нет
                if (I24hConfig::DEBUG) hd_print("Template: " . $t["template"]);
                switch ($t["template"]) {
                    case 'grid_w':
                        $folder_view = array
                        (
                            PluginRegularFolderView::async_icon_loading => true,
                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 7,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 125,
                                ViewParams::sandwich_height => 195,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,
                                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 => false,
                                ViewItemParams::icon_dx => 0,
                                ViewItemParams::icon_dy => -8,
                                ViewItemParams::icon_width => 228,
                                ViewItemParams::icon_height => 350,
                                ViewItemParams::icon_keep_aspect_ratio => false,
                            ),
                            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 => 7,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 125,
                                ViewParams::sandwich_height => 195,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,
                                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 => false,
                                ViewItemParams::icon_dx => 0,
                                ViewItemParams::icon_dy => -8,
                                ViewItemParams::icon_width => 228,
                                ViewItemParams::icon_height => 350,
                                ViewItemParams::icon_keep_aspect_ratio => false,
                            ),

                            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("2");

                        $folder_view = array
                        (
                            PluginRegularFolderView::async_icon_loading => true,
                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 7,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 125,
                                ViewParams::sandwich_height => 195,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,
                                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 => false,
                                ViewItemParams::icon_dx => 0,
                                ViewItemParams::icon_dy => -8,
                                ViewItemParams::icon_width => 228,
                                ViewItemParams::icon_height => 350,
                                ViewItemParams::icon_keep_aspect_ratio => false,
                            ),
                            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 => 7,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 125,
                                ViewParams::sandwich_height => 195,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,
                                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 => false,
                                ViewItemParams::icon_dx => 0,
                                ViewItemParams::icon_dy => -8,
                                ViewItemParams::icon_width => 228,
                                ViewItemParams::icon_height => 350,
                                ViewItemParams::icon_keep_aspect_ratio => false,
                            ),
                            PluginRegularFolderView::not_loaded_view_item_params => array
                            (
                                ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                                ViewItemParams::item_detailed_icon_path => 'missing://',
                            ),
                        );
                        break;
                    case 'promo':
                        $folder_view = array
                        (
                            PluginRegularFolderView::async_icon_loading => true,

                            PluginRegularFolderView::view_params => array
                            (
                                ViewParams::num_cols => 7,
                                ViewParams::num_rows => 2,
                                ViewParams::paint_details => false,
                                ViewParams::orientation => 'horizontal',
                                ViewParams::sandwich_width => 125,
                                ViewParams::sandwich_height => 195,
                                ViewParams::sandwich_icon_upscale_enabled => true,
                                ViewParams::sandwich_icon_keep_aspect_ratio => false,
                                ViewParams::background_path => $this->BACKGROUND,
                                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 => false,
                                ViewItemParams::icon_dx => 0,
                                ViewItemParams::icon_dy => -8,
                                ViewItemParams::icon_width => 228,
                                ViewItemParams::icon_height => 350,
                                ViewItemParams::icon_keep_aspect_ratio => false,
                            ),

                            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();
            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,
                                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':
                    if (I24hConfig::DEBUG) hd_print('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 => 400,
                            ViewParams::sandwich_height => 600,
                            ViewParams::sandwich_icon_upscale_enabled => true,
                            ViewParams::sandwich_icon_keep_aspect_ratio => true,
                            ViewParams::background_path => $this->BACKGROUND,
                            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("3");

                    $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,
                                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 => 0,
                                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;
            }
        }

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

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

    public function getCountSeries($serial_id, $season)
    {
        $url = sprintf($this->session->get_api_server() . I24hConfig::VIDEO_SERIES_LIST, $serial_id, $this->session->get_token());
        try {
            $doc = $this->session->api_call($url);
        } catch (Exception $e) {
            throw new DuneException(
                'HTTP network error', 0,
                ActionFactory::show_error(
                    true,
                    'Ошибка связи',
                    array('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
        }
        $series = 0;
        foreach ($doc 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)
    {
        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') && ($this->session->get_parental_code() != '0000')) {
                        $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 {
                if (empty($this->allow_in_packets) OR (count($this->allow_in_packets) == 0)) {
                    $defs = array();
                    ControlFactory::add_label($defs, null, 'Данный контент вам не доступен. Обратитесь к оператору!');
                    ControlFactory::add_vgap($defs, 40);
                    ControlFactory::add_button_close($defs, $this, array('button_caption_centered' => true), 'cancel', null, 'OK', 300);
                    return ActionFactory::show_dialog('Внимание!', $defs);
                } 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);
                }
            }
        } elseif ($user_input->control_id == 'to_tariffs') {
            return ActionFactory::open_folder(I24hPrivateScreen::get_media_url_str(''), 'Управление тарифами');
        } elseif ($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);
            }
//        elseif ($user_input->control_id == 'show_image') {
//        }
        } else {
            return null;
        }
    }
}

?>
