<?php

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

class I24hTopScreen extends AbstractPreloadedRegularScreen implements UserInputHandler
{
    const ID = 'top_list';
    private $amedia;
    private $vod;
    private $session;
    private $cached_movies;

    public function __construct($session, $amedia, $vod)
    {
    	$this->session = $session;
        $this->amedia = $amedia;
        $this->vod = $vod;
        $this->cached_movies = array();
        
    	parent::__construct(
            self::ID,
            array
            (
                array
                (
                    PluginRegularFolderView::async_icon_loading => false,
                    PluginRegularFolderView::view_params => array
                    (
                        ViewParams::num_cols => 5,
                        ViewParams::num_rows => 4,
                        ViewParams::paint_details => false,
                        ViewParams::paint_sandwich => true,
                        ViewParams::sandwich_base => 'gui_skin://special_icons/sandwich_base.aai',
                        ViewParams::sandwich_mask => 'cut_icon://{name=sandwich_mask}',
                        ViewParams::sandwich_cover => 'cut_icon://{name=sandwich_cover}',
                        ViewParams::sandwich_width => 350,
                        ViewParams::sandwich_height => 168,
                        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_CENTER,
                        ViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
                        ViewItemParams::item_caption_width => 1000,
                        ViewItemParams::icon_width => 320,
                        ViewItemParams::icon_height => 168,
                        ViewItemParams::item_paint_caption => false,
                    	ViewItemParams::icon_path => 'plugin_file://icons/mov_unset.png',
                    	ViewItemParams::item_detailed_icon_path => 'missing://',

                    ),

                    PluginRegularFolderView::not_loaded_view_item_params => array (),
                )
            ));
        
        UserInputHandlerRegistry::get_instance()->register_handler($this);

    }

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


    public function get_action_map(MediaURL $media_url, &$plugin_cookies)
    {
        return I24HSettings::get_top_action_map($this);
    }

    public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
    {
        return I24HSettings::get_top_menu($this,$plugin_cookies,$this->amedia,$this->session);
    }
    
    public function load_movie($movie_id)
    {

        if (I24hConfig::DEBUG) hd_print("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('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
        }

        if (empty($doc)) return null;

        $frame = '';
        $poster = '';
        $cover = '';
        foreach ($doc->img as $i) {
            if ($i->type == 'poster' && $i->ar == '16:9') {
                $poster169 = strval($i->src);
            }elseif ($i->type == 'poster' && $i->ar != '16:9'){
                $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($poster169)){
            $img = $poster169;
        }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");
        
        $this->cached_movies[$movie_id] = $movie;
        return $movie;
    	
    }

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

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

        if (I24hConfig::DEBUG) hd_print("top_screen: handle_user_input. media_url ".print_r($media_url, true));

    	if (isset($media_url->channel_id)) {
    		return ActionFactory::tv_play();
    	} else if (!empty($media_url->image) and $media_url->image == 'image'){
            ControlFactory::add_img_label($defs, '', '<icon>'.$media_url->img_src.'?h=740</icon>', 0, 0, 0);
            ControlFactory::add_vgap($defs,740);
            ControlFactory::add_close_dialog_button($defs, 'ОК', 300);
            return ActionFactory::show_dialog($media_url->name, $defs, true, 1400);
        }else{
            if ($user_input->control_id == 'goto_settings') {
                return ActionFactory::open_folder(I24hSetupScreen::get_media_url_str(''), 'Личный кабинет');
            }elseif ($user_input->control_id == 'goto_find') {
                return ActionFactory::open_folder(VodSearchScreen::get_media_url_str(), 'Поиск');
            }else{

                if (empty($media_url->is_dead)){
                    if (I24hConfig::DEBUG) hd_print("top_screen: handle_user_input!");
                    return ActionFactory::open_folder($user_input->selected_media_url);
                }else{
                    return ActionFactory::show_error(false, 'Внимание!', array('Кинотеатр недоступен',
                        'Приносим свои извинения!'));

                }

            }
    	}
    }
    
}

?>

