var dispatchWithPayload = function(key, value) {
	if (window.store) {
		window.store.dispatch({
			type: key,
			payload: value
		})
	}
}

var dispatch = function(key) {
	if (window.store) {
		window.store.dispatch({
			type: key
		})
	}
}

document.addEventListener("deviceready", function () {
  console.log( '>> Device Ready' )
  var isQuitDialogShow = false;
  var paramkeyArray = [ "ssl_cert_mode", "baidu_push_api_key", "mfp_jsonstore_collectionname", "mfp_jsonstore_username", "mfp_jsonstore_password", "iportal_referer", "android_core_vsn_num", "ios_core_vsn_num" ];

  console.log( '>> Init CustomConfigParameters' )
  CustomConfigParameters.get( function ( configData )
  {
    console.log( '[Callback] CustomConfigParameters Success' );

    window.core_vsn_num = "";
    window.app_vsn_num = "";

    if ( device.platform === 'Android' )
    {
      window.core_vsn_num = configData.android_core_vsn_num;
    } else
    {
      window.core_vsn_num = configData.ios_core_vsn_num;
    }

    window.iportal_referer = configData.iportal_referer;
    var checkDebugOrSimulatorFunc;
    var checkRootOrJailBreakFunc;
    var checkThirdPartyKeyboardFunc;
    var appLang = 'en_US';

    const getVersionCallback = ( platform, versionType) => ( version ) =>
    {
     console.debug( "platform: ", platform );
     console.debug( "versionType: ", versionType );
      console.debug( "version: ", version );

      if (versionType === "VERSION_NUMBER") { window.app_vsn_num = version }

        if ((versionType === "VERSION_NUMBER" && platform === 'iOS') || (versionType === "VERSION_CODE" && platform === 'Android')) {
            window.securityController
            .getAppDetails( device.platform, version )
            .then( ( { isVersionAllowed } ) => { if ( isVersionAllowed ) { validateDevice(); } } )
            .catch( error =>
            {
              if ( platform === 'Android' ) displayExitConfirmBox( 'mobile:common.forceUpdate', navigator.app.exitApp );
              if ( platform === 'iOS' ) displayExitConfirmBox( 'mobile:common.forceUpdate', IOSUtility.exitApp );
            } )
        }
    }

        var checkDebugCallback = function(result) {
			if (result === true || result === 'true') {
				console.log("Debug or Simulator Detected")
				var exitFunc;
				if (device.platform === 'Android') {
					exitFunc = navigator.app.exitApp;
				} else {
					exitFunc = IOSUtility.exitApp;
				}
				displayExitConfirmBox('mobile:common.generalError', exitFunc);
			}
        }

        var checkRootOrJailBreakCallback = function(result) {
			if (result === true || result === 'true') {
				console.log("Jailbreak Detected")
				var exitFunc;
				if (device.platform === 'Android') {
					exitFunc = navigator.app.exitApp;
				} else {
					exitFunc = IOSUtility.exitApp;
				}
				displayExitConfirmBox('mobile:login.msg.jailbreak', exitFunc);
			}
        }

        var checkThirdPartyKeyboardCallback = function(result) {
			if (result === "false") {
                console.log("Third Party Keyboard Detected")
                displayAlertBox('mobile:login.msg.keyboard');
			}
        }

        var displayExitConfirmBox = function(msgKey, func) {
			if(window.store && isQuitDialogShow == false) {
                isQuitDialogShow = true;
				var content = '';
				if (window.i18n) {
					content = window.i18n.t(msgKey);
				}
				window.store.dispatch({
					type: "UI_MAIN:SHOW_MESSAGE_DIALOG:S",
					value: true,
					header: '',
					title: '',
					message: content,
					singleButton: true,
					confirmButtonText: '',
					confirmButton: func
				})
			}
        }

        var displayAlertBox = function(msgKey) {
			if(window.store && isQuitDialogShow == false) {
				var content = '';
				if (window.i18n) {
					content = window.i18n.t(msgKey);
				}
				window.store.dispatch({
					type: "UI_MAIN:SHOW_MESSAGE_DIALOG:S",
					value: true,
					header: '',
					title: '',
					message: content,
					singleButton: true,
					confirmButtonText: ''
				})
			}
        }

        var validateDevice = function() {
            console.log(">> Validate Device");

            if (device.platform === 'Android') { //android specific
				checkDebugOrSimulatorFunc = androidUtils.isDebug;
				checkRootOrJailBreakFunc = window.cdvRootBeer.isRootedWithoutBusyBoxCheck;
				checkThirdPartyKeyboardFunc = androidUtils.isOEMInputMethod;

				checkThirdPartyKeyboardFunc(checkThirdPartyKeyboardCallback);
				checkDebugOrSimulatorFunc(checkDebugCallback);
				checkRootOrJailBreakFunc(checkRootOrJailBreakCallback, function() {
					console.log("Detect Rooted Android Device Fail")
				});
            } else if (device.platform === 'iOS') { //iOS specific
				checkDebugOrSimulatorFunc = IOSUtility.isDebugOrSimular;
				checkRootOrJailBreakFunc = IOSUtility.isJailBreak;

				checkDebugOrSimulatorFunc(checkDebugCallback);
				checkRootOrJailBreakFunc(checkRootOrJailBreakCallback);
			}

			//check isEmulator
			if (device.isVirtual) {
				console.log("Virtual Device Detected");
				var exitFunc;
				if (device.platform === 'Android') {
					exitFunc = navigator.app.exitApp;
				} else {
					exitFunc = IOSUtility.exitApp;
				}
				displayExitConfirmBox('mobile:common.generalError', exitFunc);
			}
        }

        var updateAppLanguage = function(langValue) {
			console.log("Update App Language=", langValue);
			if(window.store) {
				window.i18n.changeLanguage(langValue);
				window.store.dispatch({
					type: "USER:UPDATE_LOCAL_USER:S",
					data: {
						lang: langValue
					}
				})
            }
            if (device.platform === 'Android') {
                cordova.getAppVersion.getVersionCode(getVersionCallback(device.platform, "VERSION_CODE"));
            }
            cordova.getAppVersion.getVersionNumber(getVersionCallback(device.platform, "VERSION_NUMBER"));
        }

        window.JSONStoreCollectionName = device.platform === 'Android' ? configData.mfp_jsonstore_collectionname : configData.mfp_jsonstore_collectionname + "1";
        window.JSONStoreOptons = {
            username: device.platform === 'Android' ? configData.mfp_jsonstore_username : configData.mfp_jsonstore_username + "1",
            password: device.platform === 'Android' ? configData.mfp_jsonstore_password : ''
        };
        window.JSONStore;
        window.initJSONStoreCollection = function () {
			//****************************************************
			// JSONStore collection(s) setup
            //****************************************************
            var collections = {};
            collections[window.JSONStoreCollectionName] = {};
            collections[window.JSONStoreCollectionName].searchFields = {name: 'string'};

            console.log("Ready to init JSON store collection");

            window.WL.JSONStore.init(collections, window.JSONStoreOptons).then(function () {
                console.log("Init JSON store collection success");

                dispatch("DEVICE:STORAGE_INIT_OK:S");

                setTimeout(function () {
					dispatch("DEVICE:LOAD_DATA:S");
				}, 500);

                setTimeout(function() {
                    // dispatchWithPayload("USER:SYNC_USER_DATA:S", window.store.getState().user_local);
                    window.store.dispatch({
                        type: "USER:SYNC_USER_DATA:S",
                        data: window.store.getState().user_local
                    })

                    //set locale
                    navigator.globalization.getPreferredLanguage(
                        function (language) {
							console.log('[Callback] Preferred Language Success.');
							console.log('Device Language=', language);
							console.log(JSON.stringify(window.store.getState()));
                            if (!window.store.getState().app.isAcceptedSTATNC) {
								if (language.value.includes('zh-CN') || language.value.includes('zh-Hans')) {
									appLang = 'zh_CN';
								} else if (language.value.includes('zh-') || language.value.includes('zh-Hant')) {
									appLang = 'zh_HK';
                                }
                                console.log('First Time User');
                            } else {
                                console.log('Is Not First Time User.');
                                appLang = window.store.getState().user_local.lang;
                                console.log('Last Visited Language=', language);
                            }

                            updateAppLanguage(appLang);

                            window.store.dispatch({
                            type: "DEVICE:DEVICE_READY:S"
                            })
                        },
                        function () {
                            console.log('[Callback] Preferred Language Fail');
                            updateAppLanguage(appLang);

                            window.store.dispatch({
                                type: "DEVICE:DEVICE_READY:S"
                            })
                        }
                    );
                }, 2000);
            })
            .fail(function (errorObject) {
                console.log("Filed to initialize collection\n"+ JSON.stringify(errorObject));
                dispatch("DEVICE:STORAGE_INIT_OK:S");
                setTimeout(function () {
					dispatch("DEVICE:LOAD_DATA:S");
					updateAppLanguage(appLang);
				}, 2000);
            });
        }

        document.addEventListener('mfpjsonjsloaded', function () {
            console.log('>> MFPJSONJS Loaded');

            window.JSONStore = WL.JSONStore;
			window.initJSONStoreCollection();
        }, false);

        // device APIs are available
        document.addEventListener("backbutton", onBackKeyDown, false);
        // Handle the back button
        function onBackKeyDown(e) {
      /*
      let url = window.location.href;
      let pathSection = url.split('/');

      let currentSection = pathSection[pathSection.length - 2];
      let currentPage = pathSection[pathSection.length - 1];

      //home back button disable
      if (currentSection==='app' && currentPage==='home') {

        if (window.store) {
          if (window.store.getState().token.accessToken) {
            window.store.dispatch({
              type: "UI_MOBILELAYOUT:TOGGLE_LOGOUT:U"
            })
          } else {
            window.store.dispatch({
              type: "UI_MOBILELAYOUT:UI_MOBILELAYOUT_SHOW_QUIT_APP_DIALOG:U"
            })
          }
        }

            return false
        }

      //other page's back button disable
      let blockedPage = ['subscribeConfirm', 'subscribeSuccess', 'unsubscribeConfirm', 'unsubscribeSuccess','success', 'apply','calist']
      const isBlocked = blockedPage.filter(page => page === currentPage)

      if (currentSection === 'indices' || currentSection === 'trade' || currentSection === 'calist' || currentSection === 'apply') {
//          e.preventdefault();
        return false
      }

      if (isBlocked.length > 0) {
//          e.preventdefault()
        return false
      } else {
        navigator.app.backHistory();
      }
      */
            return false
        }


        //testing keyboard show/hide
        window.addEventListener('native.keyboardshow', function() {
            // console.log("######################## keyboard show")
        })

        window.addEventListener('native.keyboardhide', function() {
            dispatch("DEVICE:HIDE_KEYBOARD:U")
        })

        //show splash screen when app pause/resume
        document.addEventListener("pause", function() {
            navigator.splashscreen.show();
        }, false);

        document.addEventListener("resume", function() {
            navigator.splashscreen.hide();
        }, false);

        //cordova-plugin-network-information
        document.addEventListener("offline", function() {
            dispatch("UI_MAIN:SHOW_NETWORK_MESSAGE_DIALOG:S")
        },false)

        document.addEventListener("online", function() {
            dispatch("UI_MAIN:HIDE_NETWORK_MESSAGE_DIALOG:S")
        },false)

        //-----------------------------------------------------------------------------------
        //STA app startup routine
        //-----------------------------------------------------------------------------------

        //common
        console.log('>> Init UI');
        StatusBar.show(); //For Android StatusBar
        StatusBar.styleLightContent();
        StatusBar.backgroundColorByHexString("#000");
        screen.orientation.lock('portrait-primary');

        if (device.platform === 'iOS') { //iOS specific
            console.log('>> Init IOS Specific UI');
	        window.FirebasePlugin.grantPermission();
            StatusBar.overlaysWebView(false);
            // Keyboard.shrinkView(false); // Removed in latest version
            Keyboard.automaticScrollToTopOnHiding = true;
        }

        window.quitApp = function () {
            if (device.platform === 'Android') { //android specific
                navigator.app.exitApp();
            } else if (device.platform === 'iOS') { //iOS specific
                IOSUtility.exitApp();
            }
        }

        //Orientation
        window.changeOrientation = function (direction) {
            screen.orientation.lock(direction);
        }

        //device registration
        window.registerDevice = function (callback, callbackError) {
            try {
                if (device.platform === 'Android') {
                    var api_key = configData.baidu_push_api_key;
                    console.log(">> Register Device To Baidu")
                    baidu_push.startWork(api_key, function (result) {
                        console.log('[Callback] Baidu StartWork Success', result.data);
                        console.log(">> Register Device")
                        callback(Object.assign(result.data, { deviceOS: 'android' }));
                    }, function (error) {
                        console.error('[Callback] Baidu StartWork Fail', error);
                        callbackError(error);
                    })
                } else {
                    console.log(">> Register Device")
                    if (device.isVirtual) {
                        callback(Object.assign(true, { deviceOS: 'ios' }));
                    } else {
                        window.FirebasePlugin.getToken(function (token) {
                            // save this server-side and use it to push notifications to this device
                            console.log(token);
                            callback(Object.assign({ channelId: token }, { deviceOS: 'ios' }));
                        }, function (error) {
                            console.error(error);
                            callbackError(error);
                        });
                    }
                }
            } catch (err) {
                console.error("RegisterDevice Error: ", err)
                callbackError(err);
            }
        }

        window.unregisterDevice = function (callback, callbackError) {
            try {
                if (device.platform === 'Android') {
                    baidu_push.stopWork(function (result) {
                        console.log('[Callback] Baidu stopWork success', result);
                        callback(result);
                    }, function (error) {
                        console.error('[Callback] Baidu stoptWork fail', error);
                        callbackError(error);
                    })
                } else {
                    if (device.isVirtual) {
                        callback(true);
                    } else {
                        window.FirebasePlugin.unregister();
                    }
                }
            } catch (err) {
                console.error("UnregisterDevice Error: ", err)
                callbackError(err);
            }
        }

        cordova.plugin.http.setRequestTimeout(60);
        //cordovaHTTP for cert pinning
        console.log('>> Init Cert Pinning. Cert Pinning Mode=', configData.ssl_cert_mode);
        try{
            setSSLCertMode = cordova.plugin.http.setSSLCertMode || cordova.plugin.http.setServerTrustMode
            setSSLCertMode(configData.ssl_cert_mode, function () {
                console.log('[Callback] Cert Pinning Success.');
                window.http = cordova.plugin.http;
            }, function (err) {
                console.log('[Callback] Cert Pinning Fail. Error=', err);
            });
        }
        catch(error){
            console.log('[cordova.plugin.http] error:', error);
        }

        //-----------------------------------------------------------------------------------
        //Cordova plugin camera
        window.getPhoto = function () {

            this.photoDestinationType=navigator.camera.DestinationType;
            var source =  navigator.camera.PictureSourceType.PHOTOLIBRARY;
            var acceptMediaType = navigator.camera.MediaType.PICTURE;

            if(window.store) {
                window.store.dispatch({
                    type: "UI_CHATBOX:LOADING_ATTACHMENT:S",
                    loading: false
                })
            }

            navigator.camera.getPicture(function(data){

                var path = 'file://'+data

                if(data.startsWith('/')){
                    path = 'file://'+data
                } else {
                    path = data
                }

                // Convert image
                getFileContentAsBase64(path,function(base64Data, file){
                    var base64String = base64Data.split(',').pop();

                    if (file && !file.type.indexOf('gif') && !file.type.indexOf('jpg') && !file.type.indexOf('jpeg') && !file.type.indexOf('png') && !file.type.indexOf('pdf')) {
                        console.log('[getFileContentAsBase64] notSupportFileType=', file.type);
                        displayAlertBox('mobile:chatroom.msg.notSupportFileType');
                    } else if(file && file.size > 5242880){ // 5MB
                        console.log('[getFileContentAsBase64] overfilesize=', file.size);
                        displayAlertBox('mobile:chatroom.msg.overfilesize');
                    } else {
                        var files = {
                            name: file.name,
                            mimetype: file.type,
                            size: file.size,
                            data: base64String,
                            isFileDeleted: false
                        }

                        if(window.store) {
                            window.store.dispatch({
                                type: "UI_CHATBOX:SET_ATTACHMENT:S",
                                files
                            })
                            window.store.dispatch({
                                type: "UI_CHATBOX:LOADING_ATTACHMENT:S",
                                loading: false
                            })
                        }
                    }
                });
            }, function(data){
                window.store.dispatch({
                    type: "UI_CHATBOX:_ATTACHMENT:S",
                    loading: false
                })
                console.log('error', data)
            }, { quality: 50,
                allowEdit: false,
                destinationType: this.photoDestinationType.FILE_URI,
                sourceType: source,
                mediaType: acceptMediaType
            });
        }

        function getFileContentAsBase64(path,callback){
            window.resolveLocalFileSystemURL(path, gotFile, fail);

            function fail(e) {
                console.log('[resolveLocalFileSystemURL] fail =', e);
                displayAlertBox('mobile:chatroom.msg.cannotFindFile');
            }

            function gotFile(fileEntry) {
                fileEntry.file(function(file) {
                    file.name =  fileEntry.name;

                    var reader = new FileReader();
                    reader.onloadend = function(e) {
                        var content = this.result;
                        callback(content, file);
                        // if(file.size > 2 * 1024 * 1024){
                        //     alert('File size limit has been reached');
                        // } else {
                        //     callback(content, file);
                        // }
                    };
                    // The most important point, use the readAsDatURL Method from the file plugin
                    reader.readAsDataURL(file);
                });
            }
        }
    }, function (err) {
        console.log('[Callback] CustomConfigParameters Fail. Error=', err);
    }, paramkeyArray);
 }, false);