var http = require('http');
var express = require('express');
var request = require('request');
var openurl = require('openurl');
var path = require('path');
var qs = require('querystring');
var app = express();

module.exports = function(opts, callback) {
var port = opts.port || 8080; 		// set our port

var visorPath = path.join(opts.currentDir, opts.files);
var bookPath = path.join(visorPath, opts.index);
var nativeBookPath = bookPath.split("index.html")[0];
nativeBookPath = nativeBookPath.substring(0, nativeBookPath.length-1)

//app.use(express.static(__dirname + '/'));
app.use(express.static(nativeBookPath + '/'));

var currentDirectory = process.cwd();
console.log(currentDirectory + " __dirname: "+ __dirname);

app.listen(opts.port, function() {
//console.log('Listening on port %d', app.address().port);
});

var url = 'http://localhost:' + port + '/index.html';
//console.log(url)

openurl.open(url, function (err) {
  if (err) throw err;
  console.log('The user closed the browser');
});
//openurl.open(url);

// REST Services
app.post('/local/fetch', function(req, res) {//res.send('amit');
  var binary = '', postRes = res;
  req.on('data', function (data) {
    binary += data;
  });
  req.on('end', function () {
    var objRequest = qs.parse(binary);
    request.post(req.query.jsp, {
      form: {
        requestUrl:  objRequest.requestUrl,
        requestData: objRequest.requestData
      }
    }, function(err, res, body) {
      postRes.send(body);
    });
  });  
});

};


