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

class I24HSettings
{

//
//  UfaNet
//
    public static $VERSION          = '2.01';
    public static $API_SERVER       = 'http://api.ufanet.platform24.tv/';
    public static $PLATFORM         = 'UfaNet';
    public static $WINDOW_CAPTION   = 'UfaNet';
    public static $SHOW_DOGOVOD_AFERTA = false;
    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 function get_login_defs($session, $handler, $add_params){
        $defs = array();
        ControlFactory::add_vgap($defs, 20);
        ControlFactory::add_label($defs,null,'Друзья, для активации приложения ');
        ControlFactory::add_vgap($defs, -15);
        ControlFactory::add_label($defs,null,'обратитесь в офис АО "Уфанет" или ');
        ControlFactory::add_vgap($defs, -15);
        ControlFactory::add_label($defs,null,'позвоните по номеру 09388.');
        ControlFactory::add_vgap($defs, 20);
        //add_multiline_label($defs,'','Друзья, для активации приложения обратитесь<br>в офис АО "Уфанет" или позвоните<br>по номеру 09388',4);

        ControlFactory::add_text_field($defs,
            $handler, $add_params,
            'user_name', 'Договор:',
            '', true, false, false, false, 500);

        ControlFactory::add_vgap($defs, 20);

        ControlFactory::add_text_field($defs,
            $handler, $add_params,
            'password', 'Пароль:',
            '', true, false, false, false, 500);

        ControlFactory::add_vgap($defs, 20);

        ControlFactory::add_button($defs,
            $handler, $add_params,
            'do_login_user_by_username', ' ', 'Далее', 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 == 'do_login_user_by_username') {
            if (!preg_match('/^[0-9]{8}$/', $user_input->user_name) or (!preg_match('/^[0-9]{10}$/', $user_input->password))) {
                return array(
                    'need_close_dialog' => false,
                    'action' =>
                        ActionFactory::show_error(false,
                            'Неверный формат логина или пароля!',
                            array('Используйте формат логина (8 цифр), пароль (10 цифр)!')));

            } else {
                try {
                    $doc = $session->api_call(
                        sprintf(
                            $session->get_api_server() . I24hSession::I24H_USER_LOGIN), true,
                        array('login' => $user_input->user_name, 'password' => $user_input->password));

                    if (!empty($doc->access_token)) {
                        $session->set_token($doc->access_token);
                    } else {
                        return array(
                            'need_close_dialog' => false,
                            'action' =>
                                ActionFactory::show_error(false,
                                    'Неверный логин или пароль!',
                                    array('')));
                    }

                } catch (Exception $e) {
                    throw $session->dune_api_exception($e, 'Ошибка авторизации!.', false);
                }

                $session->clear_http_ops();

                $session->set_mbr_phone($user_input->user_name);
                $session->set_mbr_username($user_input->user_name);

                $plugin_cookies->user_name = $user_input->user_name;
                $plugin_cookies->password = $user_input->password;

                $reg_dev = $session->register_device($plugin_cookies);

                if ($reg_dev) {
                    $post_action = ActionFactory::open_folder(I24hDeviceListScreen::get_media_url_str(), self::$WINDOW_CAPTION);
                    $post_action = ActionFactory::close_dialog_and_run($post_action);
                    return array(
                        'need_close_dialog' => false,
                        'action' => $post_action
                    );
                }

                $post_action = ActionFactory::open_folder(MediaURL::encode(array('screen_id' => I24hTopScreen::ID)), self::$WINDOW_CAPTION);
                $post_action = ActionFactory::close_dialog_and_run($post_action);
                return $post_action;
            }

        }else{
            return false;
        }
    }


    public static function get_setup_user_name($session){
        return 'Договор: ' . $session->get_username();
    }

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

        $items[0] = 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'
            )
        );

        $top = $amedia->make_top_list(2);

        if (!empty($top) and is_array($top)) {
            $items = array_merge($items, $top);
        }

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

        $items[4] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hSetupScreen::ID
                    )),
            PluginRegularFolderItem::caption => 'Личный кабинет',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/settings.png'
            )
        );

        $items[5] = 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[6] = 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[7] = 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[8]= 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[9] = array
        (
            PluginRegularFolderItem::media_url =>
                MediaURL::encode(
                    array(
                        'screen_id' => I24hTopcatListScreen::ID,
                        'xcat_id' => 5,
                    )),
            PluginRegularFolderItem::caption => 'Спорт',
            PluginRegularFolderItem::view_item_params => array(
                ViewItemParams::icon_path => 'plugin_file://img/sport.png'
            )
        );

        $itemshist = array();

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

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

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

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

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

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

                    $itemshist[] = array
                    (
                        PluginRegularFolderItem::media_url =>
                            VodMovieScreen::get_media_url_str($movie['id']), // XXX: alik: hack!!
                        PluginRegularFolderItem::caption => $movie['name'],
                        PluginRegularFolderItem::view_item_params => $vip,
                    );
                }
                if ($prod['type'] == 2) {
                    if (empty($prod['serial_id'])) continue;
                    $p = $amedia->make_single_item($prod['serial_id']);
                    if (empty($p)){continue;}
                    $itemshist[] = $p;
                }
                $n++;
            }
        }
        return array_merge($items, $itemshist);
    }

    public static function get_top_action_map($session)
    {
        $top_action =
            UserInputHandlerRegistry::create_action(
                $session, 'top_action');
        return array
        (
            GUI_EVENT_KEY_ENTER => $top_action,
            GUI_EVENT_KEY_PLAY => $top_action
        );
    }
}
