EXPORTED_SYMBOLS = ["module"];
var module = function (application) {
var log = function (message) {
application.logger.debug("[VK API] " + message);
}
;
var api = application.api;
var VKAPI = function () {

}
;
VKAPI.prototype = (function (undefined) {
var init = function () {

}
;
var destroy = function () {

}
;
const API_ROOT = "https://api.vk.com/method/";
var ajax = null;
var request = function (method, params, success, error) {
var requestArguments = arguments;
authorizedRequest(function (accessToken) {
var paramsString = _getURLParamsString(params);
var url = API_ROOT + method + "?" + paramsString + "&access_token=" + accessToken;
log("api request: " + url);
if (null === ajax)
{
ajax = new application.Ajax();
}

ajax.xhr({
url: url,
type: "GET",
dataType: "json",
background: true,
success: function (data) {
if ("undefined" != typeof data.error)
{
let requestError = data.error;
handleRequestError(requestError,function repeatRequest() {
request.apply(null,requestArguments);
}
,error);
return;
}

success(data);
}
,
error: error});
}
,error);
}
;
function _getURLParamsString(params) {
var param;
return [param + "=" + encodeURIComponent(params[param]) for (param in params)].join("&");
}

var authorizedRequest = function (success, error) {
var auth = application.vkAuth;
auth.authorizedRequest(success,error);
}
;
function handleRequestError(requestError, repeatRequest, errorCallback) {
log("An error occurred. \"" + requestError.error_msg + "\"");
switch (requestError.error_code) {
case 5:
log("Get new access token and repeat request.");
let auth = application.vkAuth;
auth.resetAccessToken();
repeatRequest();
break;
default:
log("Unknown error.");
errorCallback();
break;
}

}

return {
constructor: VKAPI,
init: init,
destroy: destroy,
request: request};
}
)();
return VKAPI;
}
;
