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

class I24HSettings
{
//
//  24часаТВ
//
    public static $VERSION = '2.60';
    public static $API_SERVER = 'http://dune.platform24.tv/';
    public static $PLATFORM = 'dune-hd.tv';
    public static $WINDOW_CAPTION = 'DUNE-HD.TV';
    public static $SHOW_DOGOVOD_AFERTA = true;
    public static $CT_PRIMERA_ID = 2000;
    public static $AMEDIATEKA_ID = 1000;
    public static $MEGOGO_ID = 3000;
    public static $MEGOGO_KIDS_ID = 4000;
    public static $CT_PRIMERA_VS_ID = 2;
    public static $AMEDIATEKA_VS_ID = 1;
    public static $MEGOGO_VS_ID = 3;
    public static $MEGOGO_KIDS_VS_ID = 7;
    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 $MATRAS_URL = 'http://mp4://media.dune.platform24.tv/Dune/matras.mp4';
    public static $MATRAS_GEO_URL = 'http://mp4://media.dune.platform24.tv/Dune/geo_matras.mp4';
    public static $MEDIA_URL = 'http://media.24h.tv/';
    public static $LOCK_IMAGE = 'http://static.24h.tv/dune/channel/lock.png?w=320&h=168';


    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)
    {

        $url = sprintf($session->get_api_server() . I24hConfig::VIDEO_GENRE_LIST, $session->get_token());

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


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

        foreach ($doc 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::$MEGOGO_KIDS_ID) {
                $is_dead_megogo_kids = 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' => I24hMegogoListScreen::SCREEN_ID,
                        'is_dead' => $is_dead_megogo
                    )),
            PluginRegularFolderItem::caption => 'Megogo',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/megogo.png'
            )
        );

        $items[] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hMegogoKidsListScreen::SCREEN_ID,
                        'is_dead' => $is_dead_megogo_kids
                    )),
            PluginRegularFolderItem::caption => 'Megogo kids',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/megogo_kids.png'
            )
        );


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

        $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=180'
                )
            );

        }

        $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)) {
            if (I24hConfig::DEBUG) 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 . ")";
    }

}
