require "lol"
require "recordings"

-- Change, comment, or delete the below line
local recordings_file = "/media/USB/.Neuros/samplerecordings";

function onRequest(env, post)
	print [[<html>
		<head>
			<title>Neuros OSD - Edit scheduled recording</title>
			<link rel="stylesheet" type="text/css" href="style.css" />
		</head>
		<body><center>]];
		if post then return onPost(env, post); end
		
		local param = lol:getQueryParams(env.QUERY_STRING);
			
		if not param then
			print("<b>Please return to the <a href='index.lua'>main page</a></b>\n");
			return;
		end

		local list = recordings.loadRecordings(recordings_file);
		local rec;

		if param.id and param.id:match("^%w+$") then
			rec = list[param.id];
		elseif param.new == "true" then
			rec = list:newRecording()
		end
		
		
		if rec then 
			print ([[			
			 <h1>Edit Recording</h1>
			 
			 <form method="post" action="editrecording.lua">
			 	<input type="hidden" name="id" value=']]..(param.id or "")..[[' />
				 <table>
				 	<tr><td>Path:</td><td><input type="text" size="50" name="path" value=']]..(rec:getPath() or "")..[[' /></td></tr>]])
				 	local t = os.date("*t", rec:getStartTime() or os.time());
				 	print [[<tr><td>Start Date:</td><td>]]
				 	print ([[Day: <input type="text" size="3" name="day" value=']]..t.day..[[' /> ]])
				 	print ([[Month: <input type="text" size="3" name="month" value=']]..t.month..[[' /> ]])
				 	print ([[Year: <input type="text" size="5" name="year" value=']]..t.year..[[' />]])
				 	print("</td></tr>\n<tr>");
				 	print ([[<td>Start Time:</td><td><input type="text" size="3" name="hour" value=']]..t.hour..[[' /> : <input type="text" size="3" name="min" value=']]..t.min..[[' /></td>]])
				 	print [[</tr>]]
				 	print ([[<tr><td>Duration:</td><td><input type="text" size="3" name="dur-hour" value='1' /> : <input type="text" size="3" name="dur-min" value='0' /></td></tr>]])
		 	-- <tr><td>Path:</td><td><input type="text" size="50" name="path" value=']]..rec:getPath()..[[' /></td></tr>
				 	print [[<tr><td colspan="2"><center><input type="submit" value="Save" /></center></td></tr>]]
				 print [[</table>]]
			 	
			 	
			 	
		else
			print[[
			<b>The recording you selected cannot be found!</b>
				]];
		end
		
		print [[</center></body>
			</html>
			]]
			 	
end

function onPost(env, post)
	local form = lol:getQueryParams(getBodyData(1));
	
	local list = recordings.loadRecordings(recordings_file);
	local rec = list[form.id];
	
	if not rec then
		rec = list:newRecording();
	end
	
	print "<b>The recording has been saved</b><br/>"
	print [[<a href="index.lua">Return to main page</a>]]
	rec:setStartTime(form);
	rec:setPath(form.path);
	rec:setDuration(form["dur-hour"], form["dur-min"]);
	list:saveRecordings(recordings_file);
	
	print "\n</body>\n</html>"
end
