<?php
/**
 * Created by PhpStorm.
 * User: dkuzmichev
 * Date: 03.10.2017
 * Time: 13:03
 */

class I24HSettings
{
//
//  24часаТВ
//
    public static $VERSION = '2.54';
    public static $API_SERVER = 'https://api.24h.tv/';
    public static $PLATFORM = '24htv';
    public static $WINDOW_CAPTION = '24часаТВ';
    public static $SHOW_DOGOVOD_AFERTA = true;
    public static $CT_PRIMERA_ID = 2000;
    public static $AMEDIATEKA_ID = 1000;
    public static $MEGOGO_ID = 3000;
    public static $CT_PRIMERA_VS_ID = 2;
    public static $AMEDIATEKA_VS_ID = 1;
    public static $MEGOGO_VS_ID = 3;
    public static $LOGIN_WINDOW_WIDTH = 2000;
    public static $USERNAME_PREFIX = '';
    public static $BG_PIC = 'plugin_file://img/app_background.jpg';
    public static $CHANNELS_SORT = '';

    public static function get_login_defs($session, $handler, $add_params)
    {

        $defs = array();
        $doc = strip_tags(html_entity_decode(
            str_replace('<br>', ' ',
                str_replace('<br/>', ' ',
                    str_replace('&ndash;', '-', $session->get_provider_desc())
                )
            ),
            ENT_NOQUOTES));


        ControlFactory::add_multiline_label($defs, NULL, $doc, 8);

        ControlFactory::add_vgap($defs, 60);
        ControlFactory::add_text_field($defs,
            $handler, $add_params,
            'user_name', '                      Номер телефона:',
            '', true, false, false, false, 500);

        ControlFactory::add_vgap($defs, 20);
        ControlFactory::add_button($defs,
            $handler, $add_params,
            'reg_show_agreement', ' ', 'Далее', 500);

        $defs[] = array
        (
            GuiControlDef::name => 'close',
            GuiControlDef::title => '',
            GuiControlDef::kind => GUI_CONTROL_BUTTON,
            GuiControlDef::specific_def =>
                array
                (
                    GuiButtonDef::caption => 'Отмена',
                    GuiButtonDef::width => 500,
                    GuiButtonDef::push_action =>
                        ActionFactory::close_dialog(),
                ),
            GuiControlDef::params => null,
        );

        ControlFactory::add_vgap($defs, 20);

        return $defs;
    }


    public static function get_password($session, &$plugin_cookies, &$user_input, &$handler)
    {
        if ($user_input->control_id == 'get_password' || $user_input->control_id == 'get_sms') {

            if ($user_input->user_name === '') {
                return array(
                    'need_close_dialog' => false,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Запрос пароля',
                            array('Введите номер телефона для отправки пароля.')));
            }
            $user = $session->api_call($session->get_api_server() . I24hSession::I24H_USER, true, array(
                'username' => $user_input->user_name,
                'first_name' => $user_input->user_name,
                'email' => $user_input->user_name . '@24h.tv',
                'phone' => $user_input->user_name
            ));

            $plugin_cookies->user_name = $user_input->user_name;
            $plugin_cookies->password = (!empty($user_input->password) ? $user_input->password : '');
            $session->set_mbr_phone($user_input->user_name);
            $session->set_mbr_username($user_input->user_name);

            if (!empty($user) && (!empty($user->status_code)) && ($user->status_code == 400)) {

            } elseif (!empty($user) && (!empty($user->status_code)) && ($user->status_code == 403)) {

                return array(
                    'need_close_dialog' => false,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Ошибка!',
                            array('К сожалению, в вашем регионе работа приложения невозможна!', 'Страна: ' . $session->country, 'Город: ' . $session->city, 'IP: ' . $session->ip_address)));


            } else {
                $plugin_cookies->user_id = empty($user->id) ? 0 : $user->id;
                $plugin_cookies->provider = empty($user->provider) ? 0 : $user->provider;
            }

            $doc = $session->api_call($session->get_api_server() . I24hSession::I24H_OTPS_URL, true, array('phone' => preg_replace('/^8/', '7', $user_input->user_name)));

            if ((!empty($doc->status_code)) && ($doc->status_code == 403)) {

                return array(
                    'need_close_dialog' => true,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Ошибка!',
                            array('К сожалению, в вашем регионе работа приложения невозможна!', 'Страна: ' . $session->country, 'Город: ' . $session->city, 'IP: ' . $session->ip_address)));
            }

            $defs = array();

            ControlFactory::add_label($defs,
                null, 'Введите код высланный по SMS,',
                array('indent' => 0));
            ControlFactory::add_vgap($defs, -20);
            ControlFactory::add_label($defs,
                null, 'На номер +' . $user_input->user_name,
                array('indent' => 0));
            ControlFactory::add_vgap($defs, 30);
            ControlFactory::add_text_field($defs, $handler, null, 'password', 'Код авторизации', '', true, true, false, true, 300);
            ControlFactory::add_vgap($defs, 30);
            ControlFactory::add_close_dialog_and_apply_button($defs, $handler, array(), 'apply_subscription', 'Применить', 300);

            return array(
                'need_close_dialog' => true,
                'action' =>
                    ActionFactory::show_dialog('Авторизация', $defs, true));


        } else {
            return false;
        }

    }

    public static function get_setup_user_name($session)
    {
        return 'Учетная запись: +' . $session->get_phone();
    }

    public static function get_top_menu($top_self, &$plugin_cookies, $amedia, $session)
    {


        $headers = array();
        $headers[] = 'Accept: application/xml';
        $headers[] = 'Content-Type: application/xml';
        $doc = HD::http_get_document(sprintf($session->get_api_server() . I24hConfig::VIDEO_GENRE_LIST, $session->get_token()));

        if (is_null($doc))
            throw new Exception('Can not fetch topmovie 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: 'root'");
            throw new Exception('Invalid XML document');
        }

        $is_dead_amedia = true;
        $is_dead_ct = true;
        $is_dead_megogo = true;

        foreach ($xml->children() as $m) {
            if ($m->id ==  self::$CT_PRIMERA_ID) {
                $is_dead_ct = false;
            }
            if ($m->id ==  self::$MEGOGO_ID) {
                $is_dead_megogo = false;
            }
            if ($m->id ==  self::$AMEDIATEKA_ID) {
                $is_dead_amedia = false;
            }
        }

        $items = array();
        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => TvGroupListScreen::ID
                    )),
            PluginRegularFolderItem::caption => 'Каналы',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/air.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hAmediaListScreen::SCREEN_ID,
                        'is_dead' => $is_dead_amedia
                    )),
            PluginRegularFolderItem::caption => 'Амедиатека',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/amediateka1.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hCtprimeraListScreen::SCREEN_ID,
                        'is_dead' => $is_dead_ct
                    )),
            PluginRegularFolderItem::caption => 'ЦТ Премьера',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/ct.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hMegogoListScreen::SCREEN_ID,
                        'is_dead' => $is_dead_megogo
                    )),
            PluginRegularFolderItem::caption => 'Megogo',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/megogo.png'//'http://iptv.home-ix.ru/iptv/icons/Main/Amediateka.jpg'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url => VodSearchScreen::get_media_url_str(),
            PluginRegularFolderItem::caption => 'Поиск',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/search.png'
            )
        );


//        http://static.24h.tv/dune/filters/9000.png

        $doc = $session->api_call(sprintf($session->get_api_server() . I24hConfig::TOPCAT_LIST_URL, $session->get_token()));

        foreach ($doc as $c) {
            $items[] = array
            (
                PluginRegularFolderItem::media_url =>
                    MediaURL::encode(
                        array(
                            'screen_id' => I24hTopcatListScreen::ID,
                            'xcat_id' => $c->id,
                        )),
                PluginRegularFolderItem::caption => $c->name,
                PluginRegularFolderItem::view_item_params => array(
                    ViewItemParams::icon_path => 'http://static.24h.tv/dune/filters/' . $c->id . '.png?w=320&h=200'
                )
            );

        }


//        $items[] = array
//        (
//            PluginRegularFolderItem::media_url =>
//                MediaURL::encode(
//                    array(
//                        'screen_id' => I24hTopcatListScreen::ID,
//                        'xcat_id' => 1,
//                    )),
//            PluginRegularFolderItem::caption => 'Фильмы',
//            PluginRegularFolderItem::view_item_params => array(
//                ViewItemParams::icon_path => 'plugin_file://img/film.png'
//            )
//        );
//
//        $items[] = array
//        (
//            PluginRegularFolderItem::media_url =>
//                MediaURL::encode(
//                    array(
//                        'screen_id' => I24hTopcatListScreen::ID,
//                        'xcat_id' => 2,
//                    )),
//            PluginRegularFolderItem::caption => 'Сериалы',
//            PluginRegularFolderItem::view_item_params => array(
//                ViewItemParams::icon_path => 'plugin_file://img/serial.png'
//            )
//        );
//
//        $items[] = array
//        (
//            PluginRegularFolderItem::media_url => MediaURL::encode(
//                array(
//                    'screen_id' => I24hTopcatListScreen::ID,
//                    'xcat_id' => 3,
//                )),
//            PluginRegularFolderItem::caption => 'Детям',
//            PluginRegularFolderItem::view_item_params => array(
//                ViewItemParams::icon_path => 'plugin_file://img/kids.png'
//            )
//        );
//
//        $items[] = array
//        (
//            PluginRegularFolderItem::media_url =>
//                MediaURL::encode(
//                    array(
//                        'screen_id' => I24hTopcatListScreen::ID,
//                        'xcat_id' => 4,
//                    )),
//            PluginRegularFolderItem::caption => 'peredaci',
//            PluginRegularFolderItem::view_item_params => array(
//                ViewItemParams::icon_path => 'plugin_file://img/peredaci.png'
//            )
//        );
//
//        $items[] = array
//        (
//            PluginRegularFolderItem::media_url =>
//                MediaURL::encode(
//                    array(
//                        'screen_id' => I24hTopcatListScreen::ID,
//                        'xcat_id' => 9000,
//                    )),
//            PluginRegularFolderItem::caption => 'Спорт',
//            PluginRegularFolderItem::view_item_params => array(
//                ViewItemParams::icon_path => 'plugin_file://img/sport.png'
//            )
//        );

        $atop = $amedia->make_top_list(5);
        $itemshist = array();

        if (isset($plugin_cookies->prodhist)) {
            $prodhist = json_decode($plugin_cookies->prodhist, true);
            $n = 0;
            foreach ($prodhist as $prod) {
                if ($n >= 5) break;

                if (empty($prod['type'])) continue;
                if ($prod['type'] == 1) {

                    if (empty($prod['product_id'])) continue;

                    $movie = $top_self->load_movie($prod['product_id']);

                    if (empty($movie['id'])) continue;

                    $vip = array(ViewItemParams::icon_path => $movie['poster']);

                    $itemshist[] = array
                    (
                        PluginRegularFolderItem::media_url =>
                            VodMovieScreen::get_media_url_str($movie['id']),
                        PluginRegularFolderItem::caption => $movie['name'],
                        PluginRegularFolderItem::view_item_params => $vip,
                    );
                }
                if ($prod['type'] == 2) {
                    if (empty($prod['serial_id'])) continue;
                    $amedia_hist = $amedia->make_single_item($prod['serial_id']);

                    if (empty($amedia_hist['media_url'])) continue;
                    $itemshist[] = $amedia_hist;
                }
                $n++;

            }
        }

        return array_merge($items, $atop, $itemshist);

    }

    public static function get_top_action_map($session)
    {
        $top_action =
            UserInputHandlerRegistry::create_action(
                $session, 'top_action');

        $goto_settings =
            UserInputHandlerRegistry::create_action(
                $session, 'goto_settings');
        $goto_settings['caption'] = 'Личный кабинет';

        return array
        (
            GUI_EVENT_KEY_ENTER => $top_action,
            GUI_EVENT_KEY_PLAY => $top_action,
            GUI_EVENT_KEY_D_BLUE => $goto_settings
        );

    }

    public static function get_version()
    {

        $ver = file_get_contents(DuneSystem::$properties['install_dir_path'] . '/dune_plugin.xml');
        if (is_null($ver)) {
            hd_print('Can`t load dune_plugin.xml');
            return 'n/a';
        }
        $xml = HD::parse_xml_document($ver);
        $plugin_version = strval($xml->version);

        return self::$VERSION . "(" . $plugin_version . ")";
    }

}
