<?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();
        $doc = HD::http_get_document(
            sprintf(
                $this->session->get_api_server() . I24hConfig::MOVIE_SEARCH_URL,
                urlencode($media_url->pattern),
                $this->session->get_token(),
                $limit,
                $offset
             )
        );

        if (is_null($doc))
            throw new Exception('Can not fetch movie list');

        $xml = simplexml_load_string($doc);

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

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

        $movies = array();
        $count_video=0;
        foreach ($xml->children() as $search) {

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

                $poster = "";
                foreach ($prod->img->children() as $s) {
                    if (strval($s->type) == "poster") {
                        $poster = strval($s->src);
                        break;
                    }
                }
                $frame = "";
                foreach ($prod->img->children() as $s) {
                    if (strval($s->type) == "frame") {
                        $frame = strval($s->src);
                        break;
                    }
                }

                $vip = array(ViewItemParams::icon_path => (!empty($poster) ? $poster : $frame) . "?w=320&h=200&crop=true");
//                hd_print(">>> movie_name: " . strval($prod->title));//$movie['name']);

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

                $poster = "";
                foreach ($movie->img->children() as $s) {
                    if (strval($s->type) == "poster") {
                        $poster = strval($s->src);
                        break;
                    }
                }
                $frame = "";
                foreach ($movie->img->children() as $s) {
                    if (strval($s->type) == "frame") {
                        $frame = strval($s->src);
                        break;
                    }
                }

                $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 => (!empty($poster) ? $poster : $frame) . "?w=320&h=200&crop=true"
                    )
                );

                $itemshist[] = $video;
            }

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

        $more = false;
        if ($count_video >= $limit){$more = true;}else{hd_print("End");}
//        hd_print("from = ".$from_ndx.", total = ".($from_ndx+$limit).", count = ".$count_video);

        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)
    {
//        hd_print("SEARCHE !!!!!!!!!!!!!!!!!!!!!!! search = " . $media_url->pattern);
        $limit = 100;
        $offset = 0;
        $count_video = $limit;
        $this->session->ensure_logged_in($plugin_cookies);
        $itemshist = array();
        while ($count_video == $limit) {
//            hd_print("Iteration offset = ".$offset." , limit = ".$limit);
            $doc = HD::http_get_document(
                sprintf(
                    $this->session->get_api_server() . I24hConfig::MOVIE_SEARCH_URL,
                    urlencode($media_url->pattern),
                    $this->session->get_token(),
                    $limit,
                    $offset
                ));

            if (is_null($doc))
                throw new Exception('Can not fetch movie list');

            $xml = simplexml_load_string($doc);

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

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

            $movies = array();
            $count_video=0;
            foreach ($xml->children() as $search) {

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

                    $poster = "";
                    foreach ($prod->img->children() as $s) {
                        if (strval($s->type) == "poster") {
                            $poster = strval($s->src);
                            break;
                        }
                    }
                    $frame = "";
                    foreach ($prod->img->children() as $s) {
                        if (strval($s->type) == "frame") {
                            $frame = strval($s->src);
                            break;
                        }
                    }

                    $vip = array(ViewItemParams::icon_path => (!empty($poster) ? $poster : $frame) . "?w=320&h=200&crop=true");//$movie['poster']);
//                    hd_print(">>> movie_name: " . strval($prod->title));//$movie['name']);
                  $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;

                    $poster = "";
                    foreach ($movie->img->children() as $s) {
                        if (strval($s->type) == "poster") {
                            $poster = strval($s->src);
                            break;
                        }
                    }
                    $frame = "";
                    foreach ($movie->img->children() as $s) {
                        if (strval($s->type) == "frame") {
                            $frame = strval($s->src);
                            break;
                        }
                    }

                    $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 => (!empty($poster) ? $poster : $frame) . "?w=320&h=200&crop=true"
                        )
                    );
                    $itemshist[] = $video;
                }
                $count_video++;
            }
            $offset += $limit;
        }
        return $itemshist;
    }

    private function load_movie($movie_id)
    {
//        hd_print("function LOAD MOVIE");
//        $this->session->ensure_logged_in($plugin_cookies);

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

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

        if (is_null($doc))
            throw new Exception('Can not fetch movie info');
#        hd_print("XML-text:\n$doc\n");
        $xml = simplexml_load_string($doc);

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

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

        $poster = "";
        foreach ($xml->img->children() as $s){
            if (strval($s->type) == "poster"){
                $poster = strval($s->src);
                break;
            }
        }
        $frame = "";
        foreach ($xml->img->children() as $s){
            if (strval($s->type) == "frame"){
                $frame = strval($s->src);
                break;
            }
        }
        $movie = array(
            'id' => intval($xml->id),
            'name' =>  strval($xml->title),
            'poster' =>  !empty($poster)?$poster:$frame. "?w=320&h=200&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;
    }


}