/**
 * Copyright (c) 2020
 *
 * CENTIRM HotelTV UI-WELCOME module javascript.
 *
 * @summary short description for the file
 * @author Joel <joel.kim@centirm.com>
 *
 * Created at     : 2020-11-26 02:21:56
 * Last modified  : 2020-11-26 15:31:40
 */

HotelTV.namespace('HotelTV.ui_welcome');
HotelTV.ui_welcome = (function() {
    //// 의존 관계 선언
    let hndl_langSel = null;
    let _media_status = null;

    //// 비공개 프로퍼티

    /// 초기화 루틴
    /**
     * HotelTV UI Wrapper Function::> received event handling function
     * @param {boolean} e event
     */
    function __uifxn_WC_OnMediaEvt(e) {
        let _state = HotelTV.state;
        console.log("media_event_received = " + e.eventType);
        let _stateMedia = e.eventType;
        switch (_stateMedia) {
            case 'play_start':
                _media_status = 'playing';
                HotelTV.hcap.VideoWinSize(null);

                //Hide welcome page
                __uifxn_WC_Show(null, function() {
                    _state.menu.stage.cur = "playWelcomeMovie";

                    $('#lst_langsel').off('changed.owl.carousel');
                    $('#lst_langsel').owlCarousel('destroy');
                    $('.welcome #lst_langsel div').remove();

                    if ($(".control .skip_video").css('display') == 'none') {
                        $(".control .skip_video").fadeIn(1000);
                        setTimeout(() => {
                            $(".control .skip_video").fadeOut(3000);
                        }, 10000);
                    }
                });
                break;
            case 'play_end':
                _media_status = 'stopped';
                HotelTV.hcap.MediaShutdown(
                    function() {
                        $(".control .skip_video").hide();
                        console.log("Media Desory::Done");
                        HotelTV.UnloadWelCome();
                    },
                    function() {
                        console.log("Media Desory::Fail");
                        $(".control .skip_video").hide();
                        HotelTV.UnloadWelCome();
                    });
                break;
            case 'play_end_need_destory':
                HotelTV.hcap.MediaShutdown(
                    function() {
                        $(".control .skip_video").hide();
                        console.log("Media Desory::Done");
                        HotelTV.UnloadWelCome();
                    },
                    function() {
                        console.log("Media Desory::Fail");
                        $(".control .skip_video").hide();
                        HotelTV.UnloadWelCome();
                    });
                break;
            case 'error_in_playing':
                break;
            case 'buffer_full':
                break;
            case 'file_not_found':
                break;
            case 'network_disconnected':
                break;
            case 'network_busy':
                break;
            case 'seek_done':
                break;

            case 'play_stop_requtested':
                _media_status = 'stopped';
                HotelTV.hcap.MediaShutdown(
                    function() {
                        $(".control .skip_video").hide();
                        console.log("Media Desory::Done");
                        HotelTV.UnloadWelCome();
                    },
                    function() {
                        console.log("Media Desory::Fail");
                        $(".control .skip_video").hide();
                        HotelTV.UnloadWelCome();
                    });
                break;
        }
    }

    /**
     * HotelTV UI Wrapper Function::> received event handling function
     * @param {dictionary} _evt event information
     */
    function __uifxn_WC_OnNetEvt(_evt) {
        let _state = HotelTV.state;
        console.log("network_event_received = " + _evt.eventType);
        let _typeNetEvt = _evt.eventType;

        switch (_typeNetEvt) {
            case hcap.network.NetworkEventType.ABLE_REACH_DNS:
                break;
            case hcap.network.NetworkEventType.ABLE_REACH_GATEWAY:
                break;
            case hcap.network.NetworkEventType.ABLE_REACH_INTERNET:
                break;
            case hcap.network.NetworkEventType.DHCP_FAIL:
                break;
            case hcap.network.NetworkEventType.DHCP_SUCCESS:
                break;
            case hcap.network.NetworkEventType.ETHERNET_PLUGGED:
                break;
            case hcap.network.NetworkEventType.ETHERNET_UNPLUGGED:
                break;
            case hcap.network.NetworkEventType.IP_CONFLICT:
                break;
            case hcap.network.NetworkEventType.IP_NOT_CONFLICT:
                break;
            case hcap.network.NetworkEventType.UNABLE_REACH_DNS:
                break;
            case hcap.network.NetworkEventType.UNABLE_REACH_GATEWAY:
                break;
            case hcap.network.NetworkEventType.UNABLE_REACH_INTERNET:
                break;
            case hcap.network.NetworkEventType.UNKNOWN:
                break;
            case hcap.network.NetworkEventType.WIFI_AP_SEARCH_COMPLETE:
                break;
            case hcap.network.NetworkEventType.WIFI_CONNECT_FAIL:
                break;
            case hcap.network.NetworkEventType.WIFI_CONNECTED:
                break;
            case hcap.network.NetworkEventType.WIFI_DONGLE_PLUGGED:
                break;
            case hcap.network.NetworkEventType.WIFI_DONGLE_UNPLUGGED:
                break;
            case hcap.network.NetworkEventType.WIFI_LINK_DROPPED:
                break;
        }
    }

    /**
     * HotelTV UI Wrapper Function::> Show Welcome Hotel Logo
     * @param {boolean} uri_img background image url
     */
    function __uifxn_WC_SetHotelLogo(uri_img) {
        let _elmnt_img_hotellogo = $(".welcome > .frame > .msgwin #hotellogo");
        if (uri_img != null) {
            _elmnt_img_hotellogo.css({
                "background-image": "url(" + uri_img + ")",
                "background-size": "100% 100%"
            });
        } else {
            _elmnt_img_hotellogo.css({ "background": "none" });
        }
    }

    /**
     * HotelTV UI Wrapper Function::> Fillup welcome contents
     * @param {boolean} sz_name Guest Name
     * * @param {boolean} sz_msg Greeting Message
     */
    function __uifxn_WC_SetCtz(sz_name, sz_msg) {
        let _state = HotelTV.state;
        let _trTbl = HotelTV.translation;
        let _elmnt_guest_name = $(".welcome > .frame > .msgwin #guestname");
        let _elmnt_welcomemsg = $(".welcome > .frame > .msgwin #welcomemsg");
        let _elmnt_img_guide = $(".welcome > .frame > .guide#langsel");

        if (sz_name != null) {
            _elmnt_guest_name.html(sz_name + '<br />');
        } else {
            _elmnt_guest_name.html('<br />');
        }

        if (sz_msg[_state.lang] != null) {
            _elmnt_welcomemsg.html(sz_msg[_state.lang].replace(/(?:\r\n|\r|\n)/g, '<br>'));
        } else {
            _elmnt_welcomemsg.html('<br />');
        }
        _elmnt_img_guide.text(_trTbl.ui.welcome.guide_wc_langsel[_state.lang]);
    }

    /**
     * HotelTV UI Wrapper Function::> build welcome Main UI
     * @param {boolean} uri_img background image url
     */
    function __uifxn_WC_BldPage() {
        let _ctzOpening = HotelTV.opening;
        let _ctzWc = _ctzOpening.welcome;
        let _state = HotelTV.state;


        //Supported Language Count
        let _langCnt = Object.keys(_ctzOpening.languages).length;
        let _SupportedLang = _ctzOpening.languages;

        //Add html elements for language selection
        let _div_langsel = document.querySelector('.welcome #lst_langsel');
        for (let __lang in _SupportedLang) {
            let _div_lang_btn = document.createElement('div');
            let _sz_styleOpt = null;

            _div_lang_btn.className = 'item';
            _div_lang_btn.id = 'wc_eit_langsel_' + __lang;
            _div_lang_btn.textContent = _SupportedLang[__lang].name;
            _div_lang_btn.setAttribute("lang", __lang);
            _sz_styleOpt = "--btn_focus:url(images/bt_language_tab_focus.png); --btn_unfocus:url(images/bt_language_tab_unfocus.png);";
            _div_lang_btn.setAttribute("style", _sz_styleOpt);
            _div_langsel.appendChild(_div_lang_btn);
        }

        //
        let _start_pos = 0;
        for (let __lang in _SupportedLang) {
            if (_state.lang == __lang) {
                break;
            }
            _start_pos++;
        }
        hndl_langSel = $('#lst_langsel');
        hndl_langSel.owlCarousel({
            center: true,
            items: 3,//Number(_langCnt - 1), //Number of Items on Screen what you want
            loop: true,
            margin: 0,
            smartSpeed: 700,
            autoWidth: false,
            mouseDrag: false,
            touchDrag: false,
            pullDrag: false,
            freeDrag: false,
            startPosition: _start_pos,
        });
    }

    /**
     * HotelTV UI Wrapper Function::> show welcome Main UI
     * @param {boolean} uri_img background image url
     */
    function __uifxn_WC_Show(uri_img, _callback) {
        if (uri_img != null) {
            //Decision fist displyed language
            let _state = HotelTV.state;
            let _ctzOpening = HotelTV.opening;
            let _ctzWc = _ctzOpening.welcome;
            let _ctzGst = HotelTV.guestinfo;
            let _ctzHotel = HotelTV.hotelinfo;

            hndl_langSel = $('#lst_langsel');
            $(".welcome").show();
            $(".welcome > .frame").css("background-image", "url(" + uri_img + ")");
            $(".welcome > .frame").fadeIn(500, function() {
                hndl_langSel.show();
                //배경 출력후 1.5초 뒤에 호텔 로그와 웰컴 메시지 출력하도록 타임아웃 적용
                setTimeout(function() {
                    __uifxn_WC_SetHotelLogo(_ctzHotel.mainLogo.download);
                    setTimeout(function() {
                        $('.welcome .frame .msgwin #welcomemsg').fadeIn(500, function() {
                            $('.welcome .frame .msgwin #guestname').fadeIn(500, function() {
                                _state.menu.stage.cur = "langSel"
                            });
                        });
                    }, 500);
                }, 500);
            });



            $(document).on('keydown', function(_evt) { //attach event listener
                console.log("LANGSEL KEY EVENT::> " + _evt.keyCode);
                if (_state.menu.stage.cur == "langSel") {
                    if (_evt.keyCode == 37) {
                        $('#lst_langsel').trigger('prev.owl')
                    } else if (_evt.keyCode == 39) {
                        $('#lst_langsel').trigger('next.owl')
                    } else if (_evt.keyCode == 13) {
                        let found_dev_locale = false;
                        // SET PLATFORM LANGUAGE
                        // HotelTV.hcap.SetPlatformLanguage(_state.lang);
                        if ( 'getLocaleList' in HotelTV.devinfo )
                        {
                            for( let _localeIdx in HotelTV.devinfo.getLocaleList )
                            {
                                if ( HotelTV.devinfo.getLocaleList[_localeIdx].specifier== _state.lang ){
                                    found_dev_locale = true;
                                    break;
                                }
                            }
                        }
                        if ( found_dev_locale==true ){
                            HotelTV.hcap.SetDeviceLocale(_state.lang);
                        }else{
                            console.log("Set Default device locale set to en-US");
                            HotelTV.hcap.SetDeviceLocale('en-US');
                        }


                        // LANGUAGE 선택
                        if (_ctzWc.intro == 'image') {
                            /** Play slide shows */

                        } else if (_ctzWc.intro == 'video') {

                            /** Play movie clip */
                            HotelTV.hcap.MediaPlay(
                                _ctzWc.videos[_state.lang].download,
                                null,
                                "video/mp4",
                                1,
                                () => {
                                    console.log("STARTUP Done CB.");
                                    //Shows up skip button
                                    let _elmnt_btn_skip = $(".control .skip_video");
                                    _elmnt_btn_skip.css({
                                        "background-image": "url(" + "./images/bt_skip_en.png" + ")",
                                        "background-size": "100% 100%"
                                    });
                                },
                                () => {
                                    console.log("STARTUP Fail CB.");
                                    HotelTV.UnloadWelCome();
                                }
                            );
                        } else {
                            console.log("No welcome post contents");
                            HotelTV.UnloadWelCome();
                        }
                    }
                } else if (_state.menu.stage.cur == "playWelcomeMovie") {
                    if (_evt.keyCode == 413) {
                        // STOP KEY Event
                        if (_media_status == 'playing') {
                            _media_status = 'preparing_stop_playing';
                            var _evt = new Event('media_event_received');
                            _evt.eventType = "play_end_need_destory";
                            _evt.command_id = "event";
                            document.dispatchEvent(_evt);
                        }
                    } else {
                        console.log(">>");
                        if (_media_status == 'playing') {
                            if ($(".control .skip_video").css('display') == 'none') {
                                $(".control .skip_video").fadeIn(1000);
                                setTimeout(() => {
                                    $(".control .skip_video").fadeOut(1000);
                                }, 3000);
                            } else {
                                const _evt = new Event('media_event_received');
                                _evt['command_id'] = "media_event_received";
                                _evt['eventType'] = "play_stop_requtested";
                                document.dispatchEvent(_evt);
                            }
                        }
                    }
                }
            });



            hndl_langSel.on('changed.owl.carousel', function(event) {
                // Update Language
                console.log("LANG SEL[CHANGED]::>" + event.page.index);
                _state.lang = Object.keys(_ctzOpening.languages)[event.page.index];
                __uifxn_WC_SetCtz(_ctzGst.name, _ctzWc.message);
            });
        } else {
            //Hide welcome main frame
            if (_callback != null) {
                $(".welcome").fadeOut(1000, _callback); // display 속성을 none 으로 바꾼다.
            } else {
                $(".welcome").fadeOut(1000); // display 속성을 none 으로 바꾼다.
            }
        }
    }

    //// 공개 API
    return {
        Init: function(width, height) {
            //ADD Media related event handler
            document.addEventListener("media_event_received", __uifxn_WC_OnMediaEvt, false);
            //ADD Network related event handler
            document.addEventListener("network_event_received", __uifxn_WC_OnNetEvt, false);

            // Build up Welcome Page
            __uifxn_WC_BldPage();
        },

        Show: function() {
            let _ctzWc = HotelTV.opening.welcome;
            __uifxn_WC_Show(_ctzWc.background.file.download, null);
        },

        MqttEvent: function(_evt) {
            let _state = HotelTV.state;

            console.log("MQTT RECEVED MESSAGE::> " + _evt);
            if (_evt == "EVENT-MESSAGE-CREATE" || _evt == "EVENT-MESSAGE-UPDATE" || _evt == "EVENT-MESSAGE-DELETE") {
                //DO NOT NEED MESSAGE on WELCOME
            } else if (_evt == "EVENT-NEWS-UPDATE") {
                //DO NEW NEWS
            } else if (_evt == "EVENT-EMERGENCY-START") {

            } else if (_evt == "EVENT-EMERGENCY-STOT") {

            } else if (_evt == "COMMAND-SYSTEM-RESTART") {
                let _tmval = 10;
                let _state = HotelTV.state;
                let _trTbl = HotelTV.translation;

                HotelTV.ui_utils.ShowSysNoticeMsg(true,
                    "notice",
                    "SYSTEM NOTICE",
                    _trTbl.system.notice.event.mqtt.system_reboot[_state.lang], {
                        "timeout": _tmval,
                        "cb_disp": function() {
                            _tmval -= 1;
                            console.log("time..." + _tmval);
                            if ($('.error #countdown').css("display") == "none") {
                                $('.error #countdown').fadeIn(1000);
                            }
                            $('.error #countdown #message').text(`System will be shutdown in ${_tmval} second...`);
                        },
                        "cb_eoe": function() {
                            setTimeout(HotelTV.hcap.PwrOff(), 500);
                            HotelTV.api.ReportEvent([{'power': false, 'location':null}])
                        }
                    });
            } else if (_evt == "COMMAND-GUEST-CHECKIN") {

            } else if (_evt == "COMMAND-GUEST-CHECKOUT") {
                let _tmval = 30;
                let _state = HotelTV.state;
                let _trTbl = HotelTV.translation;

                HotelTV.ui_utils.ShowSysNoticeMsg(true,
                    "notice",
                    "SYSTEM NOTICE",
                    _trTbl.system.notice.event.mqtt.checkout[_state.lang], {
                        "timeout": _tmval,
                        "cb_disp": function() {
                            _tmval -= 1;
                            console.log("time..." + _tmval);
                            if ($('.error #countdown').css("display") == "none") {
                                $('.error #countdown').fadeIn(1000);
                            }
                            $('.error #countdown #message').text(`System will be shutdown in ${_tmval} second...`);
                        },
                        "cb_eoe": function() {
                            setTimeout(HotelTV.hcap.PwrOff(), 500);
                            HotelTV.api.ReportEvent([{'power': false, 'location':null}])
                        }
                    });
            } else if (_evt == "COMMAND-GUEST-UPDATE") {

            } else if (_evt == "COMMAND-GUEST-ROOMCHANGE") {
                let _tmval = 30;
                let _state = HotelTV.state;
                let _trTbl = HotelTV.translation;

                HotelTV.ui_utils.ShowSysNoticeMsg(true,
                    "notice",
                    "SYSTEM NOTICE",
                    _trTbl.system.notice.event.mqtt.room_change[_state.lang], {
                        "timeout": _tmval,
                        "cb_disp": function() {
                            _tmval -= 1;
                            console.log("time..." + _tmval);
                            if ($('.error #countdown').css("display") == "none") {
                                $('.error #countdown').fadeIn(1000);
                            }
                            $('.error #countdown #message').text(`System will be shutdown in ${_tmval} second...`);
                        },
                        "cb_eoe": function() {
                            setTimeout(HotelTV.hcap.PwrOff(), 500);
                            HotelTV.api.ReportEvent([{'power': false, 'location':null}])
                        }
                    });
            } else if (_evt == "COMMAND-LAB-FACTORY") {
            } else if (_evt == "COMMAND-LAB-AGING") {
            } else if (_evt == "COMMAND-LAB-SHOW-ID") {
            }
        },

        Close: function() {
            SpatialNavigation.clear();
        },


    }
})();