// Node
var util = require('util');

// Express
var express = require('express');
var bodyParser = require('body-parser');

// Express App
var app = express();
var httpProxy = require('http-proxy');
var http = require('http');
var server = http.createServer(app);

var mockApi = require('./mock-api');

// Env
var PORT = process.env.PORT || 8082;
var NODE_ENV = process.env.NODE_ENV || 'development';

app.use(bodyParser.json());

// serve the workbench files
app.use(express.static(__dirname + '/../public'));
app.use('/lib', express.static(__dirname + '/../lib'));
app.get('/modules/*', (req, res) =>
  res.sendFile(require.resolve(req.params[0]))
);

// handle url checks
app.get('/api/v2/urls/*', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  response = { success: true, type: 'audio/mpeg', statusCode: 200 };
  res.send(response);
});

server.listen(PORT, function() {
  console.log('Listen on http://localhost:' + PORT + ' in ' + NODE_ENV);
});

module.exports = {
  proxyWidgeticApi: function(auth) {
    // proxy some requests to the widgetic server
    var apiProxy = httpProxy.createProxyServer();
    var proxyWidgetic = function(req, res) {
      apiProxy.web(req, res, {
        target: 'https://widgetic.com',
        changeOrigin: true,
        secure: false,
      });
    };

    app.get('/bundles/*', proxyWidgetic);
    app.get('/assets/*', proxyWidgetic);
    app.all('/upload', proxyWidgetic);
    app.all('/upload/*', proxyWidgetic);
  },
  mockApi: function(widgetLibDir, packageInfo, config) {
    app.use('/api/v2', mockApi(widgetLibDir, packageInfo, config));
  },
  use: function() {
    app.use.apply(app, arguments);
  },
  loadDocs: function(path) {
    app.use('/docs', express.static(path));
  },
  loadBackend: function(backend) {
    require('./backend')(app, backend);
  },
};
