local mymodule = {}
validator = require("acf.validator")

mymodule.mvc = {}
mymodule.mvc.on_load = function(self, parent)
	self.model.set_processname(string.match(self.conf.prefix, "[^/]+"))
end

mymodule.default_action = "status"

function mymodule.status(self)
	return self.model.getstatus()
end

function mymodule.view(self)
	return self.model.getconfigobjects(self, self.clientdata.filename, self.sessiondata.userinfo.userid)
end

function mymodule.startstop(self)
	return self.handle_form(self, self.model.get_startstop, self.model.startstop_service, self.clientdata)
end

function mymodule.config(self)
	return self.handle_form(self, self.model.getconfig, self.model.setconfig, self.clientdata, "Save", "Edit Configuration", "Configuration Saved")
end

function mymodule.newfile(self)
	return self.handle_form(self, self.model.getnewconfigfile, function(self, value)
			return self.model.createconfigfile(self, value, self.sessiondata.userinfo.userid)
		end, self.clientdata, "Create", "Create New Config File", "Config File Created")
end

function mymodule.listfiles(self)
	return self.model.getfilelist(self, self.sessiondata.userinfo.userid)
end

function mymodule.edit(self)
	return mymodule.editfile(self)
end

function mymodule.editfile(self)
	config = self.handle_form(self, function()
			return self.model.get_filedetails(self, self.clientdata.filename, self.sessiondata.userinfo.userid)
		end, function(self, value)
			return self.model.set_filedetails(self, value, self.sessiondata.userinfo.userid)
		end, self.clientdata, "Save", "Edit Config File", "Config File Saved")
	
	if self.clientdata.linenumber and validator.is_integer(self.clientdata.linenumber) then
		config.value.filecontent.linenumber = self.clientdata.linenumber
	end
	return config
end

function mymodule.delete(self)
	return self.handle_form(self, self.model.get_remove_file, function(self, value) return self.model.remove_file(self, value, self.sessiondata.userinfo.userid) end, self.clientdata, "Delete", "Delete Config File", "Config File deleted")
end

function mymodule.listpermissions(self)
	return self.model:getpermissionslist()
end

function mymodule.edituserpermissions(self)
	return self.handle_form(self, function()
			return self.model:getuserpermissions(self.clientdata.userid)
		end, self.model.setuserpermissions, self.clientdata, "Save", "Edit User Permissions", "User permissions set")
end

function mymodule.editrolepermissions(self)
	return self.handle_form(self, function()
			return self.model:getrolepermissions(self.clientdata.role)
		end, self.model.setrolepermissions, self.clientdata, "Save", "Edit Role Permissions", "Role permissions set")
end

return mymodule
