<script src="file_wrap.js"></script>
<script src="json.js"></script>
<script>

_debug = opera.postError

// Fixed from Yusef
function staticDirectory(dir) {
	dir = opera.io.filesystem.mountSystemDirectory('application').resolve('/'+dir+'/');
	if(dir) {
		rootPath = dir.path
		dir.refresh();
		for(var i = 0, file; file = dir[i]; i++)    {
			if(file.path[file.path.lastIndexOf('/')+1]==='.') { continue; }
			if(file.isDirectory) {
				shareDirectory( file, rootPath );
			} else if (file.isFile) {
				var path = file.path.slice( rootPath.length );
				relative_uri=(rootPath+path).replace(/^\/application\//, '/');
				opera.io.webserver.shareFile(file, relative_uri);
			};
		};
	};
};

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

var state_filename = 'state_prices.json';  
var state = JSON.parse( safe_file_get(state_filename, '[]') ); 

// Register URLs
window.onload = function () {
    webserver = opera.io.webserver
    if (webserver)    {
        webserver.addEventListener('_index', start_page, false);
        webserver.addEventListener('add', add_item, false);
        webserver.addEventListener('edit', edit_item, false);
        webserver.addEventListener('delete', delete_item, false);
		staticDirectory('imgs');
        // webserver.addEventListener('_close', save_state, false);
		// This doesn't work! 
    };
};

function save_state(r) {
	safe_file_put(state_filename, JSON.stringify(state) );
};

function add_item(r) {
    var req = r.connection.request;
	if (req.bodyItems['title']) {
		// Output
	    var title = req.bodyItems['title'][0];
		state.push( {title : req.bodyItems['title'][0], price : parseFloat(req.bodyItems['price'][0]) } );
		// Save the state
		save_state(0);
	};
	var o = r.connection.response;
    o.setStatusCode(302);
    o.setResponseHeader( 'Location', webserver.currentServicePath );
    o.close()
};

function safe_html(x) {
	if (!x) {
		return '';
	} else {
		return x.toString().replace('<','<');
	};
};

function edit_item(r) {
    var req = r.connection.request;
	var o = r.connection.response;
	var id = parseInt(r.connection.request.queryItems['id'][0]);
	
	if (r.connection.request.bodyItems['_step']) {
		var title = r.connection.request.bodyItems['title'][0];
		var price = parseFloat(r.connection.request.bodyItems['price'][0]);
		if (!isNaN(price)) {
			if (id in state) {
				state[id] = {title : title, price : price }
				save_state(0);
			};
		};
		
		o.setStatusCode(302);
		o.setResponseHeader( 'Location', webserver.currentServicePath );
		o.close()
	} else {
		o.write('<form method=post>');
		if (id in state) {
			o.write('Title: <input name=title value="' + safe_html(state[id]['title']) + '"><br>');
			o.write('Price: <input name=price value="' + safe_html(state[id]['price']) + '"><br>');
			o.write('<input type=hidden name=_step value=2><br>');
			o.write('<input type=submit>');	
			o.write('</form>');	
		} else {
			o.write('Not Found?');	
		};
		o.close();
	};
};

function delete_item(r) {
    var req = r.connection.request;
	var o = r.connection.response;

	var id = parseInt(r.connection.request.queryItems['id'][0]);
	if(id in state) {
		state.remove(id);
		save_state(0);
	};

    o.setStatusCode(302);
    o.setResponseHeader( 'Location', webserver.currentServicePath );
    o.close();
};

function start_page(r) {
	var _path = webserver.currentServicePath;
    var o = r.connection.response;

	o.write('<img src="' + webserver.currentServicePath + 'imgs/worst.logo.ever.jpg">');
	o.write('<style>td { border: 1px solid black; } table { border-collapse: collapse; }</style>');
	o.write('<table><tr><td>Title<td>Price<td colspan=2>');

	for (var i=0;i<state.length;i++) {
		var p = state[i];
		o.write('<tr><td>' + p.title + '<td>' + p.price + '<td><a href='+_path+'edit?id='+i+'>edit</a><td><a href='+_path+'delete?id='+i+'>delete</a>');
	};
	o.write('</table>');
	o.write('<form method=post action="'+_path+'add">Add item:<br>Title: <input name=title autofocus> | Price: <input name=price> | <input type=submit></form>')
	o.close();
	
};
</script>