const https = require('https');
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer  = require('multer');
var exec = require('child_process').exec;

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
  next();
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var baseDir = __dirname.replace(/server\/?/, "");
var uploadDir = baseDir.replace(/\/?$/, "/upload/");
var seriesIdWrite = 0;
fs.readdirSync("data/series").forEach(function(file){seriesIdWrite = Math.max(seriesIdWrite, parseInt(file.slice(0, -5)))});

console.log('Next series id '+seriesIdWrite);
var seriesIdRead = seriesIdWrite;



app.post('/newSeries', function (req, res) {
  seriesIdWrite = 0;
fs.readdirSync("data/series").forEach(function(file){seriesIdWrite = Math.max(seriesIdWrite, parseInt(file.slice(0, -5)))});
    seriesIdRead = seriesIdWrite;
    seriesIdWrite++;
  res.send("<p>"+seriesIdWrite+"</p>");
  console.log('Next series id '+seriesIdWrite);
})

app.get('/resetSeriesRead', function (req, res) {
  seriesIdRead = seriesIdWrite;
  res.send("<p>"+seriesIdRead+"</p>");
  console.log(seriesIdRead);
})

app.post('/sendSeries', function (req, res) {

  // console.log('params');
  // console.log(req.params);
  // console.log('body');
  // console.log(req.body);
  // console.log('query');
  // console.log(req.query);
  //  console.log(req);

  var fileName = 'data/series/'+seriesIdWrite.toString()+'.json';
  console.log("storing Series "+seriesIdWrite);
  res.send(JSON.stringify(req.body));
  fs.writeFile(fileName, JSON.stringify(req.body), (error) => { console.log('Attempt to write file '+fileName); });
  seriesIdRead = seriesIdWrite;
})

app.get('/getSeriesMinus', function (req, res) {
    var seriesIdReadCurrent = seriesIdRead;
  if (seriesIdRead>1) {
    seriesIdRead--;
  }
  while (seriesIdRead>0 && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
    seriesIdRead--;
  }
  var fileName = 'data/series/'+seriesIdRead.toString()+'.json';
  if (!fs.existsSync(fileName)) {
    seriesIdRead = seriesIdReadCurrent;
    fileName = 'data/series/'+seriesIdRead.toString()+'.json';
  }
  console.log("sending series "+fileName);
  res.send(fs.readFileSync(fileName, req.body));

})

app.get('/getSeriesPlus', function (req, res) {
  var seriesIdReadCurrent = seriesIdRead;
  if (seriesIdRead<seriesIdWrite) {
    seriesIdRead++;
  }
  while (seriesIdRead<seriesIdWrite && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
    seriesIdRead++;
  }
  var fileName = 'data/series/'+seriesIdRead.toString()+'.json';
  if (!fs.existsSync(fileName)) {
    seriesIdRead = seriesIdReadCurrent;
    fileName = 'data/series/'+seriesIdRead.toString()+'.json';
  }
  console.log("sending series "+fileName);
  res.send(fs.readFileSync(fileName, req.body));
})

app.get('/removeSeries', function (req, res) { // , checkOrigin
  var fileName = 'data/series/'+seriesIdRead.toString()+'.json';
if (fs.existsSync(fileName)) {
  var seriesIdReadCurrent = seriesIdRead;
  console.log("removing series "+fileName);
  fs.unlink(fileName);
  if (seriesIdRead<seriesIdWrite) {
    seriesIdRead++;
  }
  while (seriesIdRead>seriesIdWrite && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
    seriesIdRead++;
  }
  if (seriesIdReadCurrent == seriesIdRead) {
    if (seriesIdRead>1) {
      seriesIdRead--;
    }
    while (seriesIdRead>0 && !fs.existsSync('data/series/'+seriesIdRead.toString()+'.json')) {
      seriesIdRead--;
    }
  }
}
})

app.get('/gitPull', function (req, res) {
  var exec = require('child_process').exec;
  var child;

   child = exec('git pull',
   function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
          console.log('exec error: ' + error);
      }
   });

app.get('/toto', function (req, res) {
  res.send("<p>Bonjour Toto</p>");
})

var privateKey = fs.readFileSync( '/home/lagrange/soundthings.org.key' );
var certificate = fs.readFileSync( '/home/lagrange/soundthings.org.crt' );

var server = https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(4000

// var server = app.listen(4000
, function ()
 {
  var host = server.address().address
  var port = server.address().port

  console.log("Iom node app listening at https://%s:%s", host, port)
})

// function checkOrigin (req, res, next) {
//   let origin = req.headers.origin;
//      if (!origin) {
//        origin = req.headers.referer.replace(/^(https?:\/\/[^/:]+).*$/, '$1');
//      }
//      if (origin.match(/(mathieulagrange\.github\.io|localhost)$/)) {
//        // Set CORS for the reply
//        res.header('Access-Control-Allow-Origin', origin);
//        res.header('Access-Control-Allow-Methods', 'POST, OPTIONS');
//        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
//      } else {
//        return res.send({success: false});
//      }
//      next();
// }
   res.send("pulling from git repo: "+ stdout);
})