UI.moduleBuilder['Alexa']['register_setup_pco'] = function() {
    var setupData = {
        titleImg:"Alexa/register/logo_alexa.png",
        loadingImg:"Alexa/register/loading.png",
        bgImg:UI.item_bg,
        title: "Alexa Skill Setup",
        helpText:"Alexa Skill about Hisense TV is setting up automatically. After that you can control your Hisense TV with Alexa.",
        resetHisAccountText:"Reset with the current Hisense account",
        switchAccountText:"Switch the accounts on TV",
        okBtnText:"OK",
        refreshBtnText:"Refresh",
        subHelpText:""
    }
    var template = Util.readJson("module/Alexa/register_setup_pco.json");
    var register_setup = SubModule.create(setupData, template);
    var title = UI.getItem(register_setup,"title");
    var loadingImg = UI.getItem(register_setup,"loadingImg");
    var subHelpText = UI.getItem(register_setup,"subHelpText");
    var resetHisAccount = UI.getItem(register_setup,"resetHisAccount");
    var switchAccount = UI.getItem(register_setup,"switchAccount");
    var okBtn = UI.getItem(register_setup,"okBtn");
    var refreshBtn = UI.getItem(register_setup,"refreshBtn");
    var setUpGroup = UI.getItem(register_setup,"setUpGroup");
    var successGroup = UI.getItem(register_setup,"successGroup");
    var timeoutGroup = UI.getItem(register_setup,"timeoutGroup");
    register_setup.curErrorCode = "";
    register_setup.origin = "";
    register_setup.timer = null;
    register_setup.pcoSkillName = "";
    register_setup.protected = true;


    register_setup.onPush = function(){
        register_setup.currFocus = title;
        subHelpText.alpha = setUpGroup.alpha = successGroup.alpha = timeoutGroup.alpha = 0;
        registerLoading(1);
        AVSClient.register.enablePcoSkill();
        UIObserver.subscribeMessage(UIObserver.MESSAGE_NAME.AVS_ONPCOENABLERESULT, pcoEnableCallback);
        UIObserver.subscribeMessage(UIObserver.MESSAGE_NAME.AVS_ONPCORESETRESULT, pcoResetCallback);
        if(!tv){
            var a = { "flag" : 1, "resultCode" : 0, "skillName" : "Dev Smart Home Skill for test" };
            // var a = {"resultCode":   0,"skillName":    "Hisense Smart TV"};
            // var a = {
            //     "errorCode" : "212006",
            //     "errorDesc" : "illegal parameter(212001)",
            //     "resultCode" : 1,
            //     "skillName":"cccc"
            // };
            setTimeout(function(){
                pcoEnableCallback(a);
            },2000)
        }
    };

    register_setup.onShow = function(){
        if(tv){
            try{
                pubAvsRegisterFinish();
            }catch(ex){
                DBG_ERROR(ex.message);
            }
        }
    };

    register_setup.onFocus = function(){
      if(UI.getCurrFocus().name == "title"){
          UI.base.cursor.alpha = 0;
          UI.getTween(UI.base.cursor).set({alpha: 0});
          return false;
      }else{
          return true;
      }
    };

    register_setup.onPop = function(){
        UIObserver.unsubscribeMessage(UIObserver.MESSAGE_NAME.AVS_ONPCOENABLERESULT, pcoEnableCallback);
        UIObserver.unsubscribeMessage(UIObserver.MESSAGE_NAME.AVS_ONPCORESETRESULT, pcoResetCallback);
    };

    register_setup.onkey_BACKSPACE = function(){
        Alexa.onkey_BACKSPACE();
    };

    okBtn.onkey_ENTER = function(){
        if(successGroup.alpha == 1){
            registerUpdate(1);
        }
    };

    refreshBtn.onkey_ENTER = function(){
        if(timeoutGroup.alpha == 1){
            refreshPcoFlow(register_setup.curErrorCode);
        }
    };

    resetHisAccount.onkey_ENTER = function(){
        if(setUpGroup.alpha == 1){
            refreshPcoFlow(register_setup.curErrorCode);
        }
    };

    switchAccount.onkey_ENTER = function(){
        if(setUpGroup.alpha == 1){
            if(tv){
                AVSClient.register.logout("hisense");
                AVSClient.register.logout("amazon");
                Hisense.File.delete("hisenseUI/avsRegister", 1);
            }
            clearTimeout(register_setup.timer);
            register_setup.timer = setTimeout(function(){
                Alexa.onkey_BACKSPACE();
                UI.pushSubModule("Alexa","register_bg",true);
                register_setup.timer = null;
            },2000)
        }

    };

    function refreshPcoFlow(code){
        DBG_ERROR("code is " + code + "register_setup.origin is " + register_setup.origin);
        if(code == "212006"){
          AVSClient.register.resetPcoSkill();
          register_setup.curErrorCode = "";
          return;
        }else if(code == "212007"){
            AVSClient.register.enablePcoSkill();
            register_setup.curErrorCode = "";
            return;
        }else{
            if(register_setup.origin == "enable"){
                AVSClient.register.enablePcoSkill();
                register_setup.origin = "";
                return;
            }else{
                AVSClient.register.resetPcoSkill();
                register_setup.origin = "";
                return;
            }
        }
    }

    function pcoEnableCallback(info){
        DBG_ERROR("pco enable callback " + info);
        /*MSD6586USU25-4067 for 6586 only*/
        try{
            model.avs.setEnableSkill(0);
        }catch(ex){
            DBG_ERROR(ex.message);
        }
        var result = null;
        try{
            result = JSON.parse(info);
        }catch(ex){
            DBG_ERROR(ex.message);
        }
        if (!result || result.length == 0){
            return;
        }
        registerLoading(0);
        if(!!result.skillName){
            register_setup.pcoSkillName = result.skillName;
        }
        if(!result.errorCode ){
            DBG_ERROR("enable success");
            if(result.flag == 1){// 1:can not find;  0:find
                changeHelpText("The Alexa skill called "+ register_setup.pcoSkillName +" has been enabled and set up automatically. Before using voice service, please make sure to discover your device by Alexa App or other Alexa-enabled device.");
            }else{
                changeHelpText("The Alexa skill about Hisense TV called " + register_setup.pcoSkillName + " has been enabled and set up automatically. If you want to change the settings, please download Alexa App and follow the instructions on it.");
            }
            successGroup.alpha = 1;
            setUpGroup.alpha  = timeoutGroup.alpha = 0;
            register_setup.pcoSkillName = "";
            UI.focusTo(okBtn);
        }else if(!!result.errorCode && result.errorCode == "212006"){
            DBG_ERROR("enable fail :212006");
            register_setup.curErrorCode = "212006";
            changeHelpText("Your Alexa Skill " + register_setup.pcoSkillName + " has been set up. Do you want to reset the skill with the Hisense account?");
            setUpGroup.alpha = 1;
            successGroup.alpha = timeoutGroup.alpha = 0;
            register_setup.pcoSkillName = "";
            UI.focusTo(resetHisAccount);
        }else{
            DBG_ERROR("enable fail :timeout");
            register_setup.origin = "enable";
            changeHelpText("Sorry, We are unable to respond to the request. Please press 'refresh' below to try again later.");
            timeoutGroup.alpha = 1;
            successGroup.alpha = setUpGroup.alpha = 0;
            UI.focusTo(refreshBtn);
        }
    }


    function pcoResetCallback(info){
        DBG_ERROR("pco reset callback " + info);
        /*MSD6586USU25-4067 for 6586 only*/
        try{
            model.avs.setResetSkill(0);
        }catch(ex){
            DBG_ERROR(ex.message);
        }
        var result = null;
        try{
            result = JSON.parse(info);
        }catch(ex){
            DBG_ERROR(ex.message);
        }
        if (!result || result.length == 0) {
            return;
        }
        registerLoading(0);
        if(!!result.skillName){
            register_setup.pcoSkillName = result.skillName;
        }
        if(!result.errorCode ){
            DBG_ERROR("reset success");
            if(result.flag == 1){// 1:can not find;  0:find
                changeHelpText("The Alexa skill called "+ register_setup.pcoSkillName +" has been enabled and set up automatically. Before using voice service, please make sure to discover your device by Alexa App or other Alexa-enabled device.");
            }else{
                changeHelpText("The Alexa skill about Hisense TV called " + register_setup.pcoSkillName + " has been enabled and set up automatically. If you want to change the settings, please download Alexa App and follow the instructions on it.");
            }
            successGroup.alpha = 1;
            setUpGroup.alpha  = timeoutGroup.alpha = 0;
            register_setup.pcoSkillName = "";
            UI.focusTo(okBtn);
        }else if(!!result.errorCode && result.errorCode == "212007"){
            DBG_ERROR("reset fail :212007");
            register_setup.curErrorCode = "212007";
            changeHelpText("Sorry, We are unable to respond to the request. Please press 'refresh' below to try again later.");
            timeoutGroup.alpha = 1;
            successGroup.alpha = setUpGroup.alpha = 0;
            UI.focusTo(refreshBtn);
        }else{
            BG_ERROR("reset fail :timeout");
            register_setup.origin = "reset";
            changeHelpText("Sorry, We are unable to respond to the request. Please press 'refresh' below to try again later.");
            timeoutGroup.alpha = 1;
            successGroup.alpha = setUpGroup.alpha = 0;
            UI.focusTo(refreshBtn);
        }
    }

    function registerLoading(flag) {
        if (flag) {
            loadingImg.alpha = 1;
            UI.getTween(loadingImg, true, true).to({rotation: loadingImg.rotation + Math.PI*2}, 1000);
        }
        else {
            loadingImg.alpha = 0;
            createjs.Tween.removeTweens(loadingImg);
        }
    }
    function changeHelpText(text, color){
        subHelpText.alpha = 1;
        UI.setText(subHelpText,text);
        if (!!color) {
            UI.setTextColor(subHelpText, color);
        }
        else {
            UI.setTextColor(subHelpText, 0xFFFFFF);
        }
    }
}
