//--------------------------------------------------
// Photo-booth service
// by: Alexander Terczka <alex@mail.at>
//--------------------------------------------------

// --- settings
var slideshowdir = "images/slideshow/";
var port = 8082;

// --- requires
var fs = require('fs');
var express = require('express');
var exec = require('child_process').exec;

var app = express();

var slides=[];

function read_slideshow_dir(callback)
{
    fs.readdir(slideshowdir,function (err,files) {
	if (err) { throw new Error(err); }
	slides=files;
	callback();
    });
}

//
// ----  API URLs
//
    app.get("/capture",function(req,res) {
        // Capture a photo using die capture shell script
	// and send the name to the browser or error text
        exec('./capture-photo.sh', function (error, stdout, stderr) {
  	    if (error) res.send({error: "Capture Script Fehler"});
  	    else if (stdout=="ERROR") res.send({error: "Kamera Fehler"});
  	    else res.send({image:stdout.trim()});
	});
    });

    app.get("/images.json",function(req,res) {
        res.send(slides);
    });

    app.get("/new.images.json",function(req,res) {
        // TODO: browser asks what images to show
	// server answers delayed (long polling) when nothing changed
        res.send("new.images.json");
    });

//
// ---- Client Libraries
//
    app.use("/jquery",express.static('node_modules/jquery/dist/'));

//
// ----  serve static files from "htdocs" files
//
    app.get('/', function (req, res) {
        res.sendFile(__dirname+"/htdocs/index.html");
    });

    app.use(express.static('htdocs'));
    app.use("/images",express.static('images/slideshow/'));

//
// ---- Startup
//
read_slideshow_dir(run);

// 
// ---- GO!
// 
function run()
{
    app.listen(port, function () { console.log("Photo-booth service listening on port "+port+"!"); });
}

@@ -380,24 +380,8 @@
 );%0A%0A
-var slides=%5B%5D;%0A%0A
 func
@@ -507,23 +507,8 @@
 ; %7D%0A
-%09slides=files;%0A
 %09cal
@@ -513,16 +513,21 @@
 allback(
+files
 );%0A    %7D
@@ -862,16 +862,23 @@
  (stdout
+.trim()
 ==%22ERROR
@@ -1036,21 +1036,60 @@
   re
-s.send(slides
+ad_slideshow_dir(function (data) %7B res.send(data); %7D
 );%0A 
@@ -1688,32 +1688,8 @@
 %0A//%0A
-read_slideshow_dir(run);
 %0A%0A//
@@ -1710,25 +1710,8 @@
 // %0A
-function run()%0A%7B%0A
     
@@ -1805,14 +1805,12 @@
 t+%22!%22); %7D);%0A
-%7D%0A

read slideshow dir handling changed