// var d = new Datazone('moviedb','jack','jones', 'OPTIONAL_READ_ONLY_KEY'); // If readOnlyKey is set, then it will be used instead of the username and password.
// d.createUser();
// d.setData({a:'a', c:'c', d:[1,2,3]});
// d.getData(function(d){console.log(d)});

(function(){

class Datazone {
	
	constructor(namespace, u, p, readOnlyKey = ''){
		this.username = namespace + u;
		this.password = p;
		this.readOnlyKey = readOnlyKey;
		
		//this.url = 'http://localhost/files/data.v2.php?cachebust='+ (new Date()).getTime() +'&u=' + this.username + '&p=' + this.password;
		
		this.url = 'https://files.jonnymoon.com/data.v2.php?cachebust='+ (new Date()).getTime() +'&readOnlyKey=' + readOnlyKey;
		
		
		
		if(u && p){
		    this.url = 'https://files.jonnymoon.com/data.v2.php?cachebust='+ (new Date()).getTime() +'&u=' + this.username + '&p=' + this.password;
		}
		
		this.backup_url = 'https://files.jonnymoon.com/backup.php';
	}

	async createUser() { return this.fetch(`${this.url}&cmd=create_account`); }

	async getData() { return this.fetch(`${this.url}&cmd=${this.password ? 'read' : 'read_only'}`); }

	async setData(data, {backup = null, safeWrite = true} = {}) {

		if(backup){
			// {subject: '', body:'', content_type:'text/html'};
			let backup_data = {...backup};

			backup_data.attachments = [{
				filename: 'Backup.txt',
				content_type: 'text/plain',
				content: JSON.stringify(data)
			}];

			this.fetch(this.backup_url, {data:JSON.stringify(backup_data)});
		}

		let result = await this.fetch(`${this.url}&cmd=write`, {data, safeWrite});
		if(result.__version__){
			data.__version__ = result.__version__;
		}
		return data;
	}

	async fetch(url = ``, data = {}){
		// Default options are marked with *
		let json = await fetch(url, {
			method: "POST", // *GET, POST, PUT, DELETE, etc.
			mode: "cors", // no-cors, cors, *same-origin
			cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
			credentials: "omit", // include, *same-origin, omit
			headers: { "Content-Type": "application/json" },
			redirect: "follow", // manual, *follow, error
			referrer: "no-referrer", // no-referrer, *client
			body: JSON.stringify(data), // body data type must match "Content-Type" header
		}).then(response => response.json())
		
		if(json && json.result_from_file_server === false) {
			let e = new Error(json.message);
			e.code = json.code;
			throw e;
		}
		
		return json;
	}
}

window.Datazone = Datazone;
})()



async function load(){
	let d = new Datazone('moviedb','jack','jones2');
	await d.createUser();
	let data = await d.getData();
	// data will have __version__
	data.a = 'a';
	data.b = 'b';
	data.d = [1,2,3];
	//data.__version__ = data.__version__ + 'f'
	await d.setData(data);
	console.log(data);
// d.createUser();
// d.setData({a:'a', c:'c', d:[1,2,3]});
// d.getData(function(d){console.log(d)});
}

//load();

