function getApiKeyList() {

    return tizen.keymanager.getDataAliasList();

}

function getApiKey() {
    return tizen.keymanager.getData({
        "name": "ID"
    });
}

function restore_local_storage(restore, error){
	function read_file_ext(file_name, onsuccess, onerror) {
	    console.log("Master Loader: Read file: " + file_name);
	    tizen.filesystem.resolve(
	        'camera', // Virtual root name (e.g., 'documents', 'downloads', 'images')
	        function (dir) {

	            var file = dir.resolve(file_name);
	            file.readAsText(
	                function (str) {
//	                    console.log("The file " + file_name + " content " + str);
	                    onsuccess(str);
	                },
	                function (e) {
	                    console.log('Master Loader: Error read file: ' + file_name + " " + JSON.stringify(error));
	                    onerror('Master Loader: Error read file: ' + file_name + " " + JSON.stringify(e));
	                },
	                "UTF-8");
	        },
	        function (error) {
	            console.error('Master Loader: Error resolving directory: ' + JSON.stringify(error));
	            onerror('Master Loader: Error resolving directory: ' + JSON.stringify(error));
	       },
	        'rw' // Read/write mode
	    );

	}
    tizen.filesystem.resolve("camera/local_storage.txt", function (file) {
        console.log('Master Loader: local_storage.txt exists');
//        return restore();
    	read_file_ext("local_storage.txt",
    			function (e){
    	    console.log("Master Loader: read file succes");
   		let data = JSON.parse(e);
    	    Object.keys(data).forEach(function(key) { localStorage.setItem(key, data[key])});
    	    console.log("Master Loader: Local Storage succes restored");
    	    restore();
    	}, function (e){
    		error(e);
    	});
    }, function (e) {
    	console.log("Master Loader: File local_storage.txt not found");
    	error();
    });

}


function ReadMainPage(onread, onerrorread) {

    console_log("Master Loader: Read required resolve: " + "documents/turnip_loader.html");
    tizen.filesystem.resolve("documents/turnip_loader.html",
        function(dir) {
            console_log("Master Loader: Fire read resolve: " + dir.toURI());
            onread(dir.toURI() + "?serv=" + getServerUrl() + (widget_version ? '&wvers=' + widget_version : '') + '&lvers=' + getLoaderVersion());
            return;
        },
        function(e) {
            onerrorread("Master Loader: Error " + e.message);
        },
        "r");
}

function LoadWidget(docObj, callback, onerror) {

	console.log("Master Loader Widget in " + docObj);
    var ub = getServerUrl();

    var widgetDir;


    tizen.filesystem.resolve("documents",
        function(dir) {
            console_log('Master Loader widget dir resolve');
            widgetDir = dir;
            dir.listFiles(onsuccess_resdir, onerror_resdir);
        },
        function(e) {
            console_log("Master Loader documents Load Error " + e.message);
            onerror("Master Loader: documents Load Error " + e.message);
        },
        "rw");


    function onsuccess_resdir(files) {

        filecss_count = docObj.length;
        file_del_count = files.filter(item => !item.isDirectory).length;

        console_log("Master Loader: Widget Dir " + file_del_count);

        if (file_del_count > 0) {
            for (var i = 0; i < files.length; i++) {

                if (!files[i].isDirectory) {

                    console_log("Master Loader Widget File Deleted " + files[i].fullPath);
                    widgetDir.deleteFile(files[i].fullPath,
                        function() {
                            console_log("Master Loader: Widget File Deleted ");
                            file_del_count--;
                            if (file_del_count <= 0)
                                loadWidgetContexts();
                        },
                        function(e) {
                            console_log("Master Loader Error delete widget " + e.message);
                            //блокируем ошибку удааления
                            //                      onerror("Doc delete error " + e.message);
                            file_del_count--;
                            if (file_del_count <= 0)
                                loadWidgetContexts();
                        });
                }

            }
        } else {
            loadWidgetContexts();
            return;
        }

    }

    var down_timeout;
    function loadWidgetContexts() {

        let ub = getServerUrl();

 //       let url = replaceAll(ub, "https://", "http://") + "widget_content/widget_content.zip";
        
//        let app_data = getApiKey();
        let url = replaceAll(ub, "https://", "http://") + "api/command/GetWidgetContent";

        
        console_log("Master Loader: downloadWidget widget_content.zip:" + url);
        down_timeout = setTimeout(() =>  onerror('Master Loader: downloadWidget start widget_content.zip: Timeout error'), 120000);

        var download_obj = new tizen.DownloadRequest(url, 'documents');
        tizen.download.start(download_obj, {
            onprogress: function(id, receivedSize, totalSize) {
                console_log('Master Loader: Widget Received with id: ' + id + ', ' + receivedSize + '/' + totalSize);
                if(down_timeout) clearTimeout(down_timeout);
                down_timeout = setTimeout(() =>  onerror('Master Loader: downloadWidget widget_content.zip: Timeout error'), 120000);
            },

            oncompleted: function(id, fullPath) {
                if(down_timeout) clearTimeout(down_timeout);
                console_log("Master Loader: Widget Received completed " + id + " : " + fullPath);

                let filename = fullPath.replace(/^.*[\\\/]/, '')
                console_log('Master Loader: Widget content downloaded completed: ' + filename);

                tizen.archive.open("documents/" + filename, 'r',
	                function (archive) {
	                    console_log('Master Loader: Widget content arhive open sucsess');
	                    archive.extractAll('documents',
	                    function onExtractSuccess(e) {
	                       console_log('Master Loader: Widget content arhive extract sucsess');
	                       callback();
	                    },
	                    function onExtractFail(e) {
	                        console_log("Master Loader: Extract Failed: " + JSON.stringify(e));
	                        if(down_timeout) clearTimeout(down_timeout);
	                        onerror(JSON.stringify("Master Loader: Extract Failed: " + JSON.stringify(e)));
	                    }, 
	                    function onExtractProgress(opId, val, name) {
	                        console_log('Master Loader: extracting operation (: ' + opId + ') is in progress (' + (val * 100).toFixed(1) + '%)');
	                    });
	                },         
	                function (e) {
	                    console_log('Master Loader: Error extract Widget content arhive ' + e.message);
	                    onerror('Master Loader: Error extract Widget content arhive ' + e.message);
	                }
                );
 //               callback(fullPath);
            },
            onfailed: function(id, errormsg) {
            	 console_log("Master Loader: DownloadRequest Failed with id: " + id + ", error name: " + errormsg.name);
            	 console_log(JSON.stringify(errormsg));
                 if(down_timeout) clearTimeout(down_timeout);
                onerror(JSON.stringify(errormsg));
            }
        });





    }

    /*    function loadWidgetContexts() {
        	console_log("Master Loader: Load widget context: file count = " + filecss_count);
            docObj.forEach(entry => {
            	console_log("Master Loader Widget Load Documents - Find to download " + entry);
                downloadWidget(entry,
                    function() {
                    filecss_count--;
                	console_log("Master Loader Widget File Downloaded " + entry + ", Files left = "+filecss_count);
                        if (filecss_count <= 0) {
                            callback();
                            return;
                        }
                    },
                    function(e) {
                    	console_log("Master Loader Widget download Error " + e);
                        onerror("Widget download error " + e);
                    });
                //                }

            });
        }


        function downloadWidget(item, callback, error) {

            let ub = getServerUrl();

            let url = replaceAll(ub, "https://", "http://") + "widget_content/" + item;
            console_log("Master Loader downloadWidget :" + url);

            var download_obj = new tizen.DownloadRequest(url, 'wgt-private');
            tizen.download.start(download_obj, {
                onprogress: function(id, receivedSize, totalSize) {
                    console_log('Master Loader Widget Received with id: ' + id + ', ' + receivedSize + '/' + totalSize);
                },

                oncompleted: function(id, fullPath) {
                    console_log("Master Loader Widget Received completed " + id + " : " + fullPath);
                    callback(fullPath);
                },
                onfailed: function(id, errormsg) {
                    console_log(JSON.stringify(errormsg));
                    error(JSON.stringify(errormsg));
                }
            });

        }*/



    function onerror_resdir(error) {
        console_log(
            "Master Loader The error " + error.message + " occurred when listing the files in the selected folder");
        onerror("The error " + error.message + " occurred when listing the files in the selected folder");
    }
}

function beforeRun(result) {

	get_app_id();
	
	if(widget_version === null && widget_reload === undefined && !localStorage.getItem("widget_files")){
		restore_local_storage(function(e) {
            console_log("Master Loader : Find installed widget file and restored");
            widget_version = localStorage.getItem("widget_version");
            if(widget_version && widget_version === '0.0.0') widget_version = null;
            localStorage.setItem("widget_restored", "1");
            result();
        }, function(e) {
            console_log("Master Loader : not find installed widget.");
            result();
        });
	}else{
		result();
	}


}

function get_app_id(){
	
    var aliases = tizen.keymanager.getDataAliasList();
    console_log("Master Loader ID check: " + aliases.length);

    if (aliases.length === 0) {
        widget_version = null;
        console_log("Master Loader: appID not found.");
        
    } else {
        appID = tizen.keymanager.getData({
            "name": "ID"
        });

        console_log("Master Loader appID check: " + appID);

    }
}