<?php

require_once 'lib/abstract_preloaded_regular_screen.php';
require_once 'lib/tv/tv_group_list_screen.php';

class I24hVodSeriesListScreen extends AbstractRegularScreen implements UserInputHandler
{
    const ID = 'vod_series_list';
    private $amedia;
    private $vod;
    private $session;
    private $lasy_limit = 20;

    public static function get_media_url_str($cat_id, $arg = null)
    {
        $arr['screen_id'] = self::ID;
        $arr['category_id'] = $cat_id;
        $arr['genre'] = $arg;
        return MediaURL::encode($arr);
    }

    public function __construct($session, $amedia, $vod)
    {
        $this->session = $session;
        $this->amedia = $amedia;
        $this->vod = $vod;

        parent::__construct(
            self::ID,

            array(
            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 => I24HSettings::$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://',
                ),
            ),

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

    public function get_folder_range(MediaURL $media_url, $from_ndx, &$plugin_cookies)
    {
//        hd_print("get_folder_range ".$from_ndx);
//        hd_print("VOD SERIES LIST !!!!!!!!!!!!!!!!!!!!!!! search = " . print_r($media_url,true));

        $limit = $this->lasy_limit;
        $offset = $from_ndx;
        $count_video = $limit;

        $this->session->ensure_logged_in($plugin_cookies);
        $itemshist = array();

        $limit = 20;
        $offset = $from_ndx;
        $count_video = $limit;
        $movies = array();

//        hd_print("plugin_cookies".print_r($plugin_cookies,true));

        if ($media_url->category_id == 'favorites')
        {
            $itemshist = array();
            $count_video=0;
            foreach ($this->vod->get_fav_movie_ids_from_cookies($plugin_cookies) as $f)
            {

                try {
                    $prog = $this->session->api_call(
                        sprintf(
                            $this->session->get_api_server() . I24hConfig::MOVIE_INFO_URL_FORMAT, $f, $this->session->get_token()
                        ));
                }catch (Exception $e)
                {
                    $this->vod->remove_favorite_movie($f, $plugin_cookies);
                    continue;
                }
                $frame = '';
                $poster = '';
                $cover = '';
                foreach ($prog->img as $i) {
                    if ($i->type == 'poster') {
                        $poster = $i->src;
                    }elseif ($i->type == 'frame'){
                        $frame = $i->src;
                    }elseif ($i->type == 'cover'){
                        $cover = $i->src;
                    }
                }
                if (!empty($cover)){
                    $img = $cover;
                }elseif (!empty($poster)){
                    $img = $poster;
                }else{
                    $img = $frame;
                }

                $itemshist[] = array
                (
                    PluginRegularFolderItem::media_url =>
                        VodMovieScreen::get_media_url_str($prog->id),
                    PluginRegularFolderItem::caption => $prog->title,
                    PluginRegularFolderItem::view_item_params => array(ViewItemParams::icon_path =>$img."?w=320&h=180&crop=true"),
                );
                $count_video++;
            }

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


        $count_video=0;
        foreach ($doc as $movie) {
            $frame = '';
            $poster = '';
            $cover = '';
            foreach ($movie->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;
            }

            $itemshist[] = array
            (
                PluginRegularFolderItem::media_url =>
                    VodMovieScreen::get_media_url_str(strval($movie->id)),
                PluginRegularFolderItem::caption => strval($movie->title),
                PluginRegularFolderItem::view_item_params => array(ViewItemParams::icon_path => $img."?w=320&h=180&crop=true"),
            );

            $count_video++;
        }
        $offset += $limit;

        $more = false;
        if ($count_video >= $limit){$more = true;}

        return HD::create_regular_folder_range(
            $itemshist, $from_ndx, $from_ndx+$count_video,$more);

    }

    private function load_movie($movie_id)
    {

        if (isset($this->cached_movies[$movie_id])) {
            return $this->cached_movies[$movie_id];
        }

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

        $frame = '';
        $poster = '';
        $cover = '';
        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;
        }


        $movie = array(
            'id' => intval($doc->id),
            'name' =>  strval($doc->title),
            'poster' =>  $img. "?w=320&h=180&crop=true");
      return $movie;
    }

    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        $actions = array();

        if ($this->vod->is_movie_page_supported())
            $actions[GUI_EVENT_KEY_ENTER] = ActionFactory::open_folder();
        else
            $actions[GUI_EVENT_KEY_ENTER] = ActionFactory::vod_play();

        if ($media_url->category_id == 'favorites'){

            $add_favorite_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'del_favorite');
            $add_favorite_action['caption'] = 'Удалить из избранного';

            $popup_menu_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'popup_menu');

            $actions[GUI_EVENT_KEY_D_BLUE] = $add_favorite_action;
            $actions[GUI_EVENT_KEY_POPUP_MENU] = $popup_menu_action;

        }else {

            if ($this->vod->is_favorites_supported()) {
                $add_favorite_action =
                    UserInputHandlerRegistry::create_action(
                        $this, 'add_favorite');
                $add_favorite_action['caption'] = 'Избранное';

                $popup_menu_action =
                    UserInputHandlerRegistry::create_action(
                        $this, 'popup_menu');

                $actions[GUI_EVENT_KEY_D_BLUE] = $add_favorite_action;
                $actions[GUI_EVENT_KEY_POPUP_MENU] = $popup_menu_action;
            }
        }

        return $actions;
    }


    public function get_handler_id()
    { return self::ID; }


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

        $parent_url = MediaURL::decode($user_input->parent_media_url);

        if ($user_input->control_id == 'popup_menu')
        {
            if (!isset($user_input->selected_media_url))
                return null;

            $media_url = MediaURL::decode($user_input->selected_media_url);
            $movie_id = $media_url->movie_id;

            $is_favorite = $this->vod->is_favorite_movie_id($plugin_cookies,$movie_id);

            $add_favorite_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'add_favorite');
            $del_favorite_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'del_favorite');

            $caption = $is_favorite?'Удалить из избранного':'Добавить в избранное';
            $menu_items[] = array(
                GuiMenuItemDef::caption => $caption,
                GuiMenuItemDef::action => $is_favorite?$del_favorite_action:$add_favorite_action);

            return ActionFactory::show_popup_menu($menu_items);
        }
        else if ($user_input->control_id == 'add_favorite')
        {
            if (!isset($user_input->selected_media_url))
                return null;

            $media_url = MediaURL::decode($user_input->selected_media_url);
            $movie_id = $media_url->movie_id;

            $p_m = MediaURL::decode($user_input->parent_media_url);

            $is_favorite = $this->vod->is_favorite_movie_id($plugin_cookies,$movie_id);
            if ($is_favorite)
            {
                return ActionFactory::show_title_dialog(
                    'Фильм уже находится в избранном');
            }
            else
            {
                $this->vod->add_favorite_movie($movie_id, $plugin_cookies);

                return ActionFactory::show_title_dialog(
                    'Фильм добавлен в избранное');
            }
        }else if ($user_input->control_id == 'del_favorite'){

            if (!isset($user_input->selected_media_url))
                return null;

            $media_url = MediaURL::decode($user_input->selected_media_url);
            $movie_id = $media_url->movie_id;
            $is_favorite = $this->vod->is_favorite_movie_id($plugin_cookies,$movie_id);
            if ($is_favorite) {

                $this->vod->remove_favorite_movie($movie_id, $plugin_cookies);

                if ($parent_url->category_id=='favorites') {

                    $itemshist = array();
                    $count_video = 0;
                    foreach ($this->vod->get_fav_movie_ids_from_cookies($plugin_cookies) as $f) {

                        try {
                            $prog = $this->session->api_call(
                                sprintf(
                                    $this->session->get_api_server() . I24hConfig::MOVIE_INFO_URL_FORMAT, $f, $this->session->get_token()
                                ));
                        } catch (Exception $e) {
                            $this->vod->remove_favorite_movie($f, $plugin_cookies);
                            continue;
                        }
                        $frame = '';
                        $poster = '';
                        $cover = '';
                        foreach ($prog->img as $i) {
                            if ($i->type == 'poster') {
                                $poster = $i->src;
                            }elseif ($i->type == 'frame'){
                                $frame = $i->src;
                            }elseif ($i->type == 'cover'){
                                $cover = $i->src;
                            }
                        }
                        if (!empty($cover)){
                            $img = $cover;
                        }elseif (!empty($poster)){
                            $img = $poster;
                        }else{
                            $img = $frame;
                        }
                        $itemshist[] = array
                        (
                            PluginRegularFolderItem::media_url =>
                                VodMovieScreen::get_media_url_str($prog->id),
                            PluginRegularFolderItem::caption => $prog->title,
                            PluginRegularFolderItem::view_item_params => array(ViewItemParams::icon_path => $img."?w=320&h=180&crop=true"),
                        );
                        $count_video++;
                    }

                    return ActionFactory::update_regular_folder(HD::create_regular_folder_range(
                        $itemshist, 0, $count_video, false), true);

                }else{
                       return ActionFactory::show_title_dialog(
                           'Фильм удален из избранного');
                }
            }
        }
        return null;
    }

}