//Ben Beeson
var DB_FILES;
var CURRENT_PROJECT, CURRENT_FILE;
var RECENT_FILES = []

//UI CODE
function firstTimeDB(){
	var test = localStorage.getItem('JIM_DB_SET')
	if(test == null){ //first time call
		DB_FILES = TAFFY([])
		DB_FILES.insert([dbNewFolder("Sample",0)])
		DB_FILES.insert([dbNewFile("Sample.java",defaultJava("Sample"),DB_FILES().last().id)])
		saveDB('JIM_FILES',DB_FILES)
		localStorage.setItem('JIM_DB_SET',"OK")
		localStorage.setItem('JIM_DB_LAST',DB_FILES().last().id)
		//localStorage.setItem('JIM_DB_LAST_PROJ',DB_FILES().first().id)
		
	}else DB_FILES=loadDB("JIM_FILES")
	CURRENT_FILE=localStorage.getItem('JIM_DB_LAST')
	CURRENT_FILENAME = DB_FILES({id:CURRENT_FILE}).first().name
	CURRENT_PROJECT=DB_FILES({id:CURRENT_FILE}).first().parent
	$('#projectName').html(DB_FILES({id:CURRENT_PROJECT}).first().name)
}
function listFiles(){
	var result = ""
	DB_FILES({parent:CURRENT_PROJECT}).order('name').each(function (r){
		//if(r.name.search(".class") > -1) return;
		var click = "onclick='changeFile(\""+r.id+"\")' "
		var edit =  "onclick='optionsFile(\""+r.id+"\",event);event.stopPropagation()' "
		result+='<div class="bigitem thin" '+click
				+(r.id==CURRENT_FILE?"style='background-color:skyblue; ' selected  ":" ")+'>'+r.name+
				'<span class="fileitemicon" style="float:right;" '+edit+'>&gt;</span></div><br/>'
	})
	$("#filelist").html(result)
	$("#projectname").html(DB_FILES({id:CURRENT_PROJECT}).first().name)
}
function listRecent(){
	var result = ''
	RECENT_FILES.each(function (i,item){
		var click = "onclick='changeFile(\""+item.id+"\",true);closeAllPopups()'"
		result+='<div class="bigitem thin" '+click
				+(i==0?"style='background-color:skyblue; ' selected  ":" ")+'>'+item.name+'</div><br/>'
	})
	$("#recentlist").html(result)
}
function loadLastFile(){
	$("#editor").val(DB_FILES({id:CURRENT_FILE}).first().doc)
	$('#filename').html(DB_FILES({id:CURRENT_FILE}).first().name.split(".").slice(0,-1).join("."));
	localStorage.setItem('JIM_DB_LAST',CURRENT_FILE)
	dbAddRecent(CURRENT_FILE,DB_FILES({id:CURRENT_FILE}).first().name)
}
function dbAddRecent(id,n){
	RECENT_FILES.unshift({id:id, name:n})
	var seen = []
	for(var i = 0; i < RECENT_FILES.length; i++){
		if(seen.indexOf(RECENT_FILES[i].id) > -1) {
			RECENT_FILES.splice(i,1)
			i--
			continue
		}
		seen.push(RECENT_FILES[i].id)
	}
	listRecent()
}
function dbSaveFile(){
	DB_FILES({id:CURRENT_FILE}).update({doc:$("#editor").val()})
	saveDB("JIM_FILES", DB_FILES)
	if(SYNCING) dropboxUpdate(CURRENT_FILE)
}
function dbUpdateFile(folder,name,data){
	var file = DB_FILES({parent:folder, name:name})
	var id = -1
	if(file.count() == 1) {
		file.update({doc:data,mod:new Date().getTime()})
		id = file.first().id
	}else {
		var f = dbNewFile(name,data,folder)
		DB_FILES.insert([f])
		id = f.id
	}
	saveDB("JIM_FILES", DB_FILES)
	listFiles()
}
function appendLocalClasses(p,folder){
	DB_FILES({parent:folder}).each(function (r){
		if(r.name.search(/\.class$/) > -1)
			p.push(JSON.parse(Base64.decode(r.doc.replace(/\n/g,""))))
	})
}
function changeFile(id,nofile){
	dbSaveFile()
	CURRENT_FILE=id;
	CURRENT_FILENAME = DB_FILES({id:CURRENT_FILE}).first().name
	loadLastFile()
	listFiles()
	ERRORS[id] = []
	TABBING=[]
	if(DB_FILES({id:id}).first().name.search(/\.java$/) > -1) {
		compileJava(WORKERS[CURRENT_FILE]!=null)
	}
	updateOverlay()
	if(!nofile) $('#files').toggle(150);
	$('#editor').css({height:$('#code').height(), width:$('#editor_container').width()-65})
	$('#code').css({width:$('#editor').width()-2})
}
function optionsFile(id,e){
	var row = e.target.parentNode
	var r = DB_FILES({id:id}).first()
	var edit=" onclick='deleteFile(\""+id+"\",event.target.parentNode)'"
	var rename = " onkeyup='if(event.keyCode==13) renameFile(\""+id+"\",this.value)'"
	row.onclick = null
	row.innerHTML = '<input value="'+r.name+'" '+rename+' class="textfile"/><span class="fileitemicon" style="float:right;background-color:transparent" '+edit+'>X</span></div><br/>'
}
function renameFile(id,v){
	DB_FILES({id:id}).update({name:v})
	saveDB("JIM_FILES", DB_FILES)
	listFiles()
}
function deleteFile(id,elem){
	if(!elem || confirm("Comfirm delete '"+DB_FILES({id:id}).first().name+"'")){
		if(!elem || elem.getAttribute('selected')==null){
			DB_FILES({id:id}).remove()
			saveDB("JIM_FILES", DB_FILES)
			listFiles()
		}else alert("File is currently open, cannot delete")
	}
}
function dbPurgeClasses(){
	var purge = true
	while(purge){
		purge = false
		DB_FILES({parent:CURRENT_PROJECT}).each(function (r){
			if(purge) return;
			if(r.name.search(".class") > -1){
				purge = true
				deleteFile(r.id)
				return;
			}
		})
	}
	
}
function uiAddFile(){
	var name = UI.textValue('fileName')
	var auth = UI.textValue('authorName')
	var type = UI.listSelected('fileType')
	if(name == "") {
		alert("file name required")
		UI.textValueHighlight('fileName','missing')
	}else{
		var content = ""
		var ext = ""
		if(type == 0) {
			content = defaultJava(name)
			ext = ".java"
		}else if(type == 1) {
			content = defaultApplet(name)
			ext = ".java"
		}
		var old = CURRENT_FILE
		var id = dbAddFile(CURRENT_PROJECT,name+ext,auth,content)
		if(id == -1){
			alert("file already exists")
			UI.textValueHighlight('fileName','missing')
			return;
		}
		CURRENT_FILE = old
		toggleDialog('newfile')
		changeFile(id)
	}
}
function dbAddFile(p,n,a,c){
	if(DB_FILES({parent:p, name:n}).count() > 0) return -1 //error has occurred
	var time = new Date().getTime()
	var f = new DB_FILE(n,true,p,c,time,time,a)
	DB_FILES.insert([f])
	saveDB("JIM_FILES", DB_FILES)
	CURRENT_FILE = f.id
	return f.id
}
function dbAddFolder(n,a,s){
	if(DB_FILES({parent:0, name:n}).count() > 0) return true //error has occurred
	var time = new Date().getTime()
	var f = new DB_FILE(n,false,0,"",time,time,a,s)
	DB_FILES.insert([f])
	saveDB("JIM_FILES", DB_FILES)
	CURRENT_PROJECT = f.id
}
function defaultJava(name){return "public class "+name+'{\n\tpublic static void main(String args[]){\n\t\tSystem.out.println("Hello World!");\n\t}\n}'}
function defaultApplet(name){
	return 'import java.applet.Applet;\nimport java.awt.Graphics;\npublic class '+name+' extends Applet{\n\tpublic void init(){\n\t\tSystem.out.println("Applet Initialised");\n\t}\n\tpublic void paint(Graphics g){\n\t\tg.drawString("Hello World!",100,100);\n\t}\n}'}

FILES = {
	getID: function (parent,name){return DB_FILES({parent:parent, name:name}).first().id},
	getName: function (id){return DB_FILES({id:id}).first().name},
	getFile: function (parent,name){return DB_FILES({parent:parent, name:name}).first()},
	exists: function (parent,name){return DB_FILES({parent:parent, name:name}).count() > 0},
	iterateFolder: function (parent,callback){DB_FILES({parent:parent}).each(callback)}
}

//DB FUNCTIONS
function loadDB(name) {return TAFFY(JSON.parse(localStorage.getItem(name)))}
function saveDB(name,db) {localStorage.setItem(name, JSON.stringify(db().get()))}
function UID() {return new Date().getTime()}

function dbNewFile(name,con,parent){return new DB_FILE(name,true,parent,con)}
function dbNewFolder(name,parent){return new DB_FILE(name,false,parent,"")}
function DB_FILE(name,file,parent,doc,cr,mod,a,s){
	this.name = name
	this.cr = cr
	this.mod = mod
	this.file = file
	this.parent = parent
	this.doc = doc
	this.auth = a
	this.sync = s
	this.id = ''+UID()+DB_FILES().count()
}
