/* globals Rkns */
/* Saves the Full JSON at each modification */
Rkns.mtdcJsonIO = function(_renkan, _opts) {
var _proj = _renkan.project;
if (typeof _opts.http_method === 'undefined') {
_opts.http_method = 'PUT';
}
var _load = function() {
_proj.set({
loadingStatus : true
});
Rkns.$.getJSON(_opts.url, function(_data) {
_renkan.dataloader.load(_data);
_renkan.setCurrentUser(_opts.user_id, _opts.user_name);
_proj.set({
loadingStatus : false
});
_proj.set({
saveStatus : 0
});
_proj.on('add:nodes add:edges add:users add:views', function(_model) {
_model.on('change remove', function() {
_thrSave();
});
_thrSave();
});
_proj.on('change', function() {
if (!(_proj.changedAttributes.length === 1 && _proj
.hasChanged('saveStatus'))) {
_thrSave();
}
});
_proj.get('nodes').each(function(_node) {
_node.on('change remove', function() {
_thrSave();
});
});
_proj.get('edges').each(function(_edge) {
_edge.on('change remove', function() {
_thrSave();
});
});
_proj.get('users').each(function(_user) {
_user.on('change remove', function() {
_thrSave();
});
});
}).fail(function(jqXHR, textStatus) {
_showErrorModal(jqXHR, textStatus);
});
};
var _save = function() {
_proj.set({
saveStatus : 2
});
var _data = _proj.toJSON();
if (!_renkan.read_only) {
Rkns.$.ajax({
type : _opts.http_method,
url : _opts.url,
contentType : 'application/json',
data : JSON.stringify(_data),
success : function(data) {
_proj.set({
saveStatus : 0,
updated : data.updated
});
},
error: function (jqXHR, textStatus, errorThrown) {
_showErrorModal(jqXHR, textStatus, errorThrown);
}
});
}
};
var _thrSave = Rkns._.debounce(_save, 1000);
Rkns.$('#renkanErrorReload').on('click', function(){
location.reload();
});
var errorModal = document.getElementById('renkanErrorModal');
var _showErrorModal = function(jqXHR) {
errorModal.style.display = 'block';
switch(jqXHR.status){
case 400:
var jsonResp = JSON.parse(jqXHR.responseText);
if(jsonResp.hasOwnProperty('validation_timestamp')){
document.getElementById('400Error_timestamp').style.display = 'block';
}
else {
Rkns.$('#400Error_other').append(jqXHR.responseText);
document.getElementById('400Error_other').style.display = 'block';
}
break;
case 403:
document.getElementById('403Error').style.display = 'block';
break;
case 404:
document.getElementById('404Error').style.display = 'block';
break;
case 500:
Rkns.$('#500Error').append(jqXHR.responseText);
document.getElementById('500Error').style.display = 'block';
break;
case 503:
document.getElementById('503Error').style.display = 'block';
break;
}
};
_load();
};