<?php

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

class I24hSearchScreen extends AbstractRegularScreen implements UserInputHandler
{
    const ID = 'search';
    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['page_name'] = $cat_id;
        $arr['pattern'] = $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)
    {
        $limit = $this->lasy_limit;
        $offset = $from_ndx;
        $count_video = $limit;

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

        $url = sprintf($this->session->get_api_server() . I24hConfig::MOVIE_SEARCH_URL, urlencode($media_url->pattern), $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('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
        }

        $movies = array();
        $count_video=0;
        foreach ($doc as $search) {

            if (!empty($search->program)) {
                $prod = $search->program;

                $frame = '';
                $poster = '';
                $cover = '';
                foreach ($prod->img as $i) {
                    if ($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($poster)){
                    $img = $poster;
                }else{
                    $img = $frame;
                }

                $vip = array(ViewItemParams::icon_path => $img . "?w=320&h=180&crop=true");

                $itemshist[] = array
                (
                    PluginRegularFolderItem::media_url =>
                        VodMovieScreen::get_media_url_str(strval($prod->id)),
                    PluginRegularFolderItem::caption => strval($prod->title),
                    PluginRegularFolderItem::view_item_params => $vip,
                );
            }

            if (!empty($search->video)) {
                $movie = $search->video;

                $frame = '';
                $poster = '';
                $cover = '';
                $poster169 = '';
                foreach ($movie->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 == 'poster_3_4' && $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($poster169)) {
                    $img = $poster169;
                }elseif (!empty($poster)){
                    $img = $poster;
                }elseif (!empty($cover)){
                    $img = $cover;
                }else{
                    $img = $frame;
                }

                $mediaurl = MediaURL::encode(
                    array(
                        'screen_id' => "amedia_list",
                        'serial_id' => strval($movie->id)
                    ));

                $video = array
                (
                    PluginRegularFolderItem::media_url => $mediaurl,
                    PluginRegularFolderItem::caption => strval($movie->title),
                    PluginRegularFolderItem::view_item_params => array(
                        ViewItemParams::icon_path => $img . "?w=320&h=180&crop=true"
                    )
                );

                $itemshist[] = $video;
            }

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

        $more = false;
        if ($count_video >= $limit){$more = true;}else{hd_print("End");}

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

    }

    public function get_all_folder_items_old(MediaURL $media_url, &$plugin_cookies)
    {
        $limit = 100;
        $offset = 0;
        $count_video = $limit;
        $this->session->ensure_logged_in($plugin_cookies);
        $itemshist = array();
        while ($count_video == $limit) {

            $url = sprintf($this->session->get_api_server() . I24hConfig::MOVIE_SEARCH_URL, urlencode($media_url->pattern), $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('Не удаётся подключиться к серверу.', 'Проверьте подключение к сети Интернет.')));
            }

            $movies = array();
            $count_video = 0;
            foreach ($doc as $search) {

                if (!empty($search->program)) {
                    $prod = $search->program;

                    $frame = '';
                    $poster = '';
                    $cover = '';
                    foreach ($doc->img as $i) {
                        if ($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($poster)){
                        $img = $poster;
                    }elseif (!empty($cover)){
                        $img = $cover;
                    }else{
                        $img = $frame;
                    }

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

                if (!empty($search->video)) {
                    $movie = $search->video;

                    $frame = '';
                    $poster = '';
                    $cover = '';
                    foreach ($doc->img as $i) {
                        if ($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($poster)){
                        $img = $poster;
                    }elseif (!empty($cover)){
                        $img = $cover;
                    }else{
                        $img = $frame;
                    }

                    $mediaurl = MediaURL::encode(
                        array(
                            'screen_id' => "amedia_list",
                            'serial_id' => strval($movie->id)
                        ));

                    $video = array
                    (
                        PluginRegularFolderItem::media_url => $mediaurl,
                        PluginRegularFolderItem::caption => strval($movie->title),
                        PluginRegularFolderItem::view_item_params => array(
                            ViewItemParams::icon_path => $img . "?w=320&h=180&crop=true"
                        )
                    );
                    $itemshist[] = $video;
                }
                $count_video++;
            }
            $offset += $limit;
        }
        return $itemshist;
    }

    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' && $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($poster)){
            $img = $poster;
        }elseif (!empty($cover)){
            $img = $cover;
        }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 ($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)
    {
//        hd_print('Vod favorites: handle_user_input:');
//        foreach ($user_input as $key => $value)
//            hd_print("  $key => $value");

        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($movie_id);
            $add_favorite_action =
                UserInputHandlerRegistry::create_action(
                    $this, 'add_favorite');
            $caption = 'Добавить в избранное';
            $menu_items[] = array(
                GuiMenuItemDef::caption => $caption,
                GuiMenuItemDef::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;

            $is_favorite = $this->vod->is_favorite_movie_id($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(
                    'Фильм добавлен в избранное');
            }
        }

        return null;
    }


}