// Init
UI.moduleBuilder['FTE']['fte_source'] = function(){
    var sourceData = {
        backgroundImg: UI.window_bg,
        titleText: "[SE3220]"//"Select your primary input source"
    };
    var template = Util.readJson("module/FTE/fte_source.json");
    var source = SubModule.create(sourceData, template);

    var SOURCE_UID_TV = 0;   //TV的uid为0
    var SOURCE_PLAYID_TV = "TV";
    source.pageData = {
        "allInputsData": [],
        "currSource": "ANT/Cable",
        "sourceItem": [
            //id, name, signal, lock, rename
            "0", "ANT/Cable", "0", "1", "", "",
            "1", "AV", "1", "1", "", "",
            "2", "COMPONENT", "0", "0", "ComponentComponent", "",
            "3", "HDMI1", "0", "0", "", "",
            "4", "HDMI2", "0", "0", "", "",
            "5", "HDMI3", "1", "0", "", "",
            "6", "HDMI4", "1", "0", "", ""
        ],
        "sortSequence": [
            "HDMI1",
            "HDMI2",
            "HDMI3",
            "HDMI4",
            "ANT/CABLE",
            "AV",
            "COMPONENT"
        ],
        "sourceTimer":null,
        "focus":false,
        "sourceNum":0
    };

    var liveTV = window[LIVETV.MAIN];
    var tiles = UI.getItem(source, "tiles");

    function getInputsDataForFTE(){
        var inputsData = initAllInputsData();
        DBG_ERROR("inputsData is " + objToString(inputsData));
        var list = sortInputsData(inputsData);
        DBG_ERROR(" SORT list is " + objToString(list));
        var showData = [];
        try{
            var sourceInfo ={"signal":true,"uid":1,"channelName":"TV12345678WWWWWWWWWTTTTT"};
//            var sourceInfo = liveTV.getCurrentSourceObj(); //当前已选择的信号源
            sourceInfo.uid = getCurrentSourceId();
            DBG_ERROR("sourceInfo.uid is" + sourceInfo.uid);
        }catch(e){
            DBG_ERROR("getInputsDataForFTE(): " + e.message);
        }

        for(var i = 0; i < list.length; i++) {
            var item ={};
            item = list[i];
            DBG_ERROR("item is " + objToString(item));
            var sourceAssetsName = list[i].uid;
            if (list[i].id == SOURCE_UID_TV) {
                sourceAssetsName = "tv";
            }
            if(list[i].id == sourceInfo.uid){
                item.img = "FTE/fte_input_" + sourceAssetsName + "_selected.png";
            }
            else {
                if(list[i].signal == 0) {
                    item.img = "FTE/fte_input_" + sourceAssetsName + "_activated.png";
                }else{
                    item.img = "FTE/fte_input_" + sourceAssetsName + ".png";
                }
            }
            showData.push($.extend(true,{},item));
        }
        DBG_ERROR("getInputsDataForFTE:" + objToString(showData));
        return showData;
    }

    /*function fteGetInputsData(){
        var ITEM_NUM = 6;
        var signalSourceList = [], allSourceList = [], sourceArr = [],noSignalSourceList = [];
        var inputsData = {};
        var sourceItem = source.pageData.sourceItem;
        try{
            if(tv) {
                sourceItem = model.source.getInputName();
            }
            DBG_INFO("fteGetInputsData: sourceItem:" + objToString(sourceItem));
            var locked = false;
            var TVNoSignal = tv ? liveTV.getHasChannelFlag(): false;
//            var TVNoSignal = false;
            for (var i = 0; i < sourceItem.length / ITEM_NUM; i++) {
                if (sourceItem[i * ITEM_NUM] == 0 && !TVNoSignal) {
                    sourceItem[i * ITEM_NUM + 2] = 1;
                }

                if (sourceItem[i * ITEM_NUM + 3] == 1) {
                    locked = true;
                }else{
                    locked = false;
                }
                sourceArr.push({
                    id: sourceItem[i * ITEM_NUM],
                    name: sourceItem[i * ITEM_NUM + 1],
                    signal: sourceItem[i * ITEM_NUM + 2],
                    lock: sourceItem[i * ITEM_NUM + 3],
                    locked: locked,
                    rename: sourceItem[i * ITEM_NUM + 4]
                });
                allSourceList.push(sourceItem[i * ITEM_NUM]);
                if (sourceItem[i * ITEM_NUM + 2] == 0) {
                    signalSourceList.push(sourceItem[i * ITEM_NUM]);
                }else {
                    noSignalSourceList.push(sourceItem[i * ITEM_NUM]);
                }
            }
            inputsData.allSourceList = allSourceList;
            inputsData.signalSourceList = signalSourceList;
            inputsData.noSignalSourceList = noSignalSourceList;
            inputsData.sourceList = sourceArr;
            DBG_INFO("fteGetInputsData: return inputsData:" + objToString(inputsData));
            return inputsData;
        }catch(e){
            DBG_ERROR("fteGetInputsData: " + e.message);
        }
    }*/

    function sortInputsData(sourceInputData) {
        //对信号顺序排序
        var showSourceList = [];
        for(var i = 0 ; i< source.pageData.sortSequence.length ; i++){
            for(var j = 0; j < sourceInputData.sourceList.length ; j++){
                if (sourceInputData.sourceList[j].name.toUpperCase().replace(" ", "") == source.pageData.sortSequence[i]) {
                    showSourceList.push(sourceInputData.sourceList[j]);
//                    DBG_ERROR("showSourceList is " + objToString(showSourceList));
                    break;
                }
            }
        }
        for (var i = 0; i < showSourceList.length; i++) {
            showSourceList[i].uid = showSourceList[i].name.toLowerCase().replace(" ", "");
        }
        return showSourceList;
    }
//})();

/*-------------------------------------------Actions---------------------------------------------------*/
//(function(){
    var fteBackground = UI.getSubModule("fte_background");

    source.onPush = function() {
        fteBackground.alpha = 0;
        source.pageData.focus = false;
        fteSourceDetectChanged();
//        var sourceInfo = liveTV.getCurrentSourceObj();
        var sourceInfo ={ "uid":"0","innerId":2,"name":"ANT/Cable","noSignal":false,"isLock":false,"rename":"ANT/Cable","hotelLock":false};
        sourceInfo.uid = getCurrentSourceId();
        var index = _getIndexById(source.pageData.allInputsData, sourceInfo.uid);
        sourceInfo.name = source.pageData.allInputsData[index].name;
        DBG_ERROR("sourceInfo.uid is " + sourceInfo.uid + " index is " + index + " sourceInfo.name is " + sourceInfo.name );
        source.pageData.currSource = sourceInfo.name.toUpperCase().replace(" ", "");
        DBG_ERROR("FTE source.pageData.currSource is " + source.pageData.currSource);
//        source.currFocus = UI.getItem(source, "fteSource_" + source.pageData.currSource);
        UI.focusTo(UI.getItem(source, "fteSource_" + source.pageData.currSource));
        UI.clearFteMenuTimeout();
        UIObserver.subscribeMessage(UIObserver.MESSAGE_NAME.SOURCE_DETECT_CHANGED, fteSourceDetectChanged);
    };
    source.afterPush = function() {
        setWizardStep(0);   //到信号源页就算FTE完成了
        setWizardSetFlag(0);
        if (tv) {
            resumeDTV();
        }
    };
    source.onPop = function() {
        UIObserver.unsubscribeMessage(UIObserver.MESSAGE_NAME.SOURCE_DETECT_CHANGED, fteSourceDetectChanged);
    };
    source.onShow = function() {
        source.alpha = 1;
        source.visible = true;
        UI.updateStage();
    };
    source.onkey_BACKSPACE = function() {
        tiles.onkey_ENTER(UI.getCurrFocus());
    };
    source.onkey_EXIT = function() {
        tiles.onkey_ENTER(UI.getCurrFocus());
    };

    tiles.onFocus = function(focus) {
        var currentIndex = tiles.initSequence.indexOf(focus);
        if(source.pageData.focus == false){
            if (currentIndex != (tiles.initSequence.length - 1)) {    //current source is not NONE
                var currentType = source.pageData.allInputsData[currentIndex].id;
                try {
                    DBG_INFO("changeSourceTo " + currentType+ " source.pageData.allInputsData[currentIndex].playId is " +source.pageData.allInputsData[currentIndex].playId);
                    try {
                        if(tv){
                            model.source.setSystemDefaultInput(source.pageData.allInputsData[currentIndex].playId);
                            setLiveTVSystemDefaultInput();
                        }
                        clearSourceTimeout();
                        source.pageData.sourceTimer = setTimeout(function(){
                            changeSourceTo(currentType);
                        },3000);
                    } catch (e) {
                        DBG_ERROR(e.message)
                    }
//                UIObserver.publishMessage(UIObserver.MESSAGE_NAME.SOURCE_DETECT_CHANGED, 'AVS-2');
                }
                catch (ex) {
                    DBG_ERROR("fte_source tiles.onFocus: " + ex.message);
                }
            }else{
                try {
                    model.source.setSystemDefaultInput(SOURCE_PLAYID_TV);
                    setLiveTVSystemDefaultInput();
                    clearSourceTimeout();
                    source.pageData.sourceTimer = setTimeout(function(){
                        changeSourceTo(SOURCE_UID_TV);
                    },3000);
                } catch (e) {
                    DBG_ERROR(e.message);
                }
            }
        }

        return true;
    };


    function fteSourceDetectChanged() {    //刷新信号源列表
        DBG_ERROR("fteSourceDetectChanged: source detect changed");
        var focusIndex = 0;
        if (UI.getCurrSubModule().name == "fte_source") {
            focusIndex = _getIndex(tiles.initSequence, UI.getCurrFocus());
        }
        source.pageData.allInputsData = getInputsDataForFTE();
        var siData = source.pageData.allInputsData;
        tiles.removeAllChildren();
        var array = [];
        for (var i=0; i < siData.length; i++) {
            array.push({});
            array[i].name = "fteSource_" +  siData[i].name.replace(" ", "");
            array[i].bgImg = UI.item_bg;
            array[i].sourceImg = siData[i].img;
            if (!!siData[i].rename && siData[i].rename != "") {
                array[i].sourceText = siData[i].rename;
            }
            else {
                array[i].sourceText = siData[i].name;
            }
        }
        //增加None信号选择
        array.push({});
        array[array.length - 1].name = "fteSource_" + "NONE";
        array[array.length - 1].bgImg = UI.item_bg;
        array[array.length - 1].sourceImg = "FTE/fte_input_none.png";
        array[array.length - 1].sourceText = "NONE";
        var info = {
            template : "fte_source_item",
            direction : CONST.GIRD_DIRECTION.H,
            breakNum : 2,
            distanceX : 12,
            distanceY : 12,
            container : tiles,
            x : 0,
            y : 0
        };
        Gird.create(array, info);

        for (var i = 0; i < tiles.initSequence.length - 1; i++) {
            tiles.initSequence[i].signal = siData[i].signal;    //有无信号
        }
        tiles.initSequence[tiles.initSequence.length - 1].signal = 1;   //None永远设为无信号

        if (UI.getCurrSubModule().name == "fte_source") {
            focusIndex = focusIndex > 0? focusIndex: 0;
            UI.focusTo(tiles.initSequence[focusIndex]);
        }
        source.pageData.sourceNum = siData.length + 1;
        if(source.pageData.sourceNum == 7){
            tiles.initSequence[tiles.initSequence.length -2 ].onkey_DOWN = function(){
                UI.focusTo(tiles.initSequence[tiles.initSequence.length -1 ]);
            }
        }

    }

    function sourceSetNormalImg(tar) {
        var oldName = "fteSource_" +  tar;
        var oldObj = UI.getItem(tiles, oldName);
        var oldUid = source.pageData.currSource.toLocaleLowerCase().replace(" ", "");
        var sourceAssetsName = oldUid;
        if (oldUid == "ant/cable") {
            sourceAssetsName = "tv";
        }
        if(oldObj.signal == 0) {
            UI.setImage(oldObj.children[1], "FTE/fte_input_" + sourceAssetsName + "_activated.png");
        }else{
            UI.setImage(oldObj.children[1], "FTE/fte_input_" + sourceAssetsName + ".png");
        }
        UI.updateStage();
    }

    function sourceSetFocusImg(tar) {
        var newName = "fteSource_" +  tar;
        var newObj = UI.getItem(tiles, newName);
        var newUid = source.pageData.currSource.toLocaleLowerCase().replace(" ", "");
        var sourceAssetsName = newUid;
        if (newUid == "ant/cable") {
            sourceAssetsName = "tv";
        }
        UI.setImage(newObj.children[1], "FTE/fte_input_" + sourceAssetsName + "_selected.png");
        UI.updateStage();
    }

    tiles.onkey_ENTER = function(focus) {
        source.pageData.focus = true;
        var currentSourceIndex = tiles.initSequence.indexOf(focus);
        if (currentSourceIndex != (tiles.initSequence.length - 1)){
            var currentSourceType = source.pageData.allInputsData[currentSourceIndex].id;
            try{
                DBG_INFO("onkey enter changeSourceTo " + currentSourceType);
                clearSourceTimeout();
                changeSourceTo(currentSourceType);
            }catch(ex){
                DBG_ERROR(ex.message);
            }
        }
        if (source.pageData.currSource == focus.name.split("_")[1]) {
            DBG_INFO("current source is: " + source.pageData.currSource);
            if(g_fteNoneSource.none){
                g_fteNoneSource.needUpdate = true;
            }
            g_fteNoneSource.none = false;
            setTimeout(function() {
                source.alpha = 0;
                FTE.play4kVideo(isStartEpos);
            }, 200);
        }else {
            sourceSetNormalImg(source.pageData.currSource);
            source.pageData.currSource = focus.name.split("_")[1];  //更新当前选择记录
            sourceSetFocusImg(source.pageData.currSource);
            var currentIndex = tiles.initSequence.indexOf(focus);
            if (source.pageData.currSource == "NONE") {  //选择none，进入Launcher
//                UI.setImage(tiles.initSequence[currentIndex].children[1], "FTE/fte_input_none_selected.png");
//                //tiles.initSequence[currentIndex].updateCache();
//                DBG_INFO("current index on enter: " + currentIndex + ", source id: " + "NONE");
                try {
                    model.source.setSystemDefaultInput(SOURCE_PLAYID_TV);
                    setLiveTVSystemDefaultInput();
                } catch (e) {
                    DBG_ERROR(e.message)
                }
                clearSourceTimeout();
                changeSourceTo(SOURCE_UID_TV);      //设置通道为TV
                DBG_INFO("go to launcher");
                if(!g_fteNoneSource.none){
                    g_fteNoneSource.needUpdate = true;
                }
                g_fteNoneSource.none = true;
                setTimeout(function() {
                    FTE.isOpenLiveTV = false;
                    source.alpha = 0;
                    FTE.play4kVideo(function () {
                        if (!!source.param && !!source.param.modeIndex) {
                            isStartEpos();
                        }
                        else {
                            UI.popAllModule();
                            UI.pushModule("launcher");
                        }
                    });
                }, 200)
            }
            else {
//                var currentType = source.pageData.allInputsData[currentIndex].id;
//                var currentTypeUid = source.pageData.allInputsData[currentIndex].uid;
//                UI.setImage(tiles.initSequence[currentIndex].children[1], "FTE/fte_input_" + currentTypeUid + "_selected.png", tiles.initSequence[currentIndex]);
////            tiles.initSequence[currentIndex].updateCache();
//                DBG_INFO("current index on enter: " + currentIndex + ", source id: " + currentType);
                if(g_fteNoneSource.none){
                    g_fteNoneSource.needUpdate = true;
                }
                g_fteNoneSource.none = false;
                setTimeout(function() {
                    source.alpha = 0;
                    FTE.play4kVideo(isStartEpos);
                }, 200)

            }
        }
        UI.updateStage();
    };

    function isStartEpos() {
        if (!!source.param && !!source.param.modeIndex) {   //modeIndex是2或者1才有效
            //调用相应接口,启动e-Pos
            try{
                model.system.setUserMode(source.param.modeIndex);
            }catch(e){
                DBG_ERROR(e.message);
            }
            UI.setEposMenuTimeout(startRetailmodeTimer,retailmodeTimeout);
            startePos(true);
        }
    }
    function clearSourceTimeout(){
        if(!!source.pageData.sourceTimer){
            clearTimeout(source.pageData.sourceTimer);
        }
        source.pageData.sourceTimer = null;
    }

};