'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _bodyParser = require('body-parser');

var _bodyParser2 = _interopRequireDefault(_bodyParser);

var _cookieParser = require('cookie-parser');

var _cookieParser2 = _interopRequireDefault(_cookieParser);

var _expressSession = require('express-session');

var _expressSession2 = _interopRequireDefault(_expressSession);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _config = require('./config.json');

var _config2 = _interopRequireDefault(_config);

var _appUtils = require('./server/utils/appUtils');

var _appUtils2 = _interopRequireDefault(_appUtils);

var _configUtil = require('./server/utils/configUtil');

var _configUtil2 = _interopRequireDefault(_configUtil);

var _constants = require('./server/constants.js');

var _constants2 = _interopRequireDefault(_constants);

var _viewsController = require('./server/controllers/viewsController');

var _viewsController2 = _interopRequireDefault(_viewsController);

var _buildController = require('./server/controllers/api/buildController');

var _buildController2 = _interopRequireDefault(_buildController);

var _publishingController = require('./server/controllers/api/publishingController');

var _publishingController2 = _interopRequireDefault(_publishingController);

var _fogController = require('./server/controllers/api/fogController');

var _fogController2 = _interopRequireDefault(_fogController);

var _winstonLogs = require('./server/utils/winstonLogs');

var _winstonLogs2 = _interopRequireDefault(_winstonLogs);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * *******************************************************************************
 *  * Copyright (c) 2018 Edgeworx, Inc.
 *  *
 *  * This program and the accompanying materials are made available under the
 *  * terms of the Eclipse Public License v. 2.0 which is available at
 *  * http://www.eclipse.org/legal/epl-2.0
 *  *
 *  * SPDX-License-Identifier: EPL-2.0
 *  *******************************************************************************
 *
 */

var express = require('express');

var path = require('path');


var startServer = function startServer(port) {
  var app = void 0,
      dbPort = void 0,
      sslKey = void 0,
      sslCert = void 0,
      intermedKey = void 0;

  app = initApp();

  _configUtil2.default.getAllConfigs().then(function () {
    if (!port) {
      dbPort = _configUtil2.default.getConfigParam(_constants2.default.CONFIG.port);
      if (dbPort) {
        port = dbPort;
      } else {
        port = _config2.default.port;
      }
    }

    sslKey = _configUtil2.default.getConfigParam(_constants2.default.CONFIG.ssl_key);
    if (sslKey) {
      sslCert = _configUtil2.default.getConfigParam(_constants2.default.CONFIG.ssl_cert);
      intermedKey = _configUtil2.default.getConfigParam(_constants2.default.CONFIG.intermediate_cert);
      startHttpsServer(app, port, sslKey, sslCert, intermedKey);
    } else {
      startHttpServer(app, port);
    }
  });
};

var initApp = function initApp() {
  var app = express();

  // parse application/x-www-form-urlencoded
  app.use(_bodyParser2.default.urlencoded({
    extended: true
  }));
  // parse application/json
  app.use(_bodyParser2.default.json());
  app.engine('ejs', require('ejs').renderFile);
  app.set('view engine', 'ejs');
  app.use((0, _cookieParser2.default)());
  // app.use(expressSession({secret:'someSecretTokenHere'}));

  app.set('views', path.join(__dirname, 'views'));
  app.use(express.static(__dirname + '/public'));
  app.use(express.static(__dirname + '/../client_uploads/'));

  app.get('/login', _viewsController2.default.loginPage);
  app.get('/password/reset', _viewsController2.default.resetUserPasswordPage);
  app.get('/account/activate/resend', _viewsController2.default.resendActivationEmailPage);
  app.get('/signup', _viewsController2.default.userSignupPage);
  app.get('/account/activate/code/:code', _viewsController2.default.activateAccountPage);

  app.get('/authoring/build', _viewsController2.default.authenticateUser, _viewsController2.default.buildPage);
  app.get('/authoring/publishing', _viewsController2.default.authenticateUser, _viewsController2.default.publishingPage);
  app.get('/authoring/fog', _viewsController2.default.authenticateUser, _viewsController2.default.fogPage);
  app.get('/authoring/account', _viewsController2.default.authenticateUser, _viewsController2.default.accountPage);
  app.get('/profile/update', _viewsController2.default.authenticateUser, _viewsController2.default.updateProfilePage);
  app.get('/password/change', _viewsController2.default.authenticateUser, _viewsController2.default.updateUserPasswordPage);
  app.get('/account/delete', _viewsController2.default.authenticateUser, _viewsController2.default.deleteUserAccountPage);
  app.get('/logout', _viewsController2.default.authenticateUser, _viewsController2.default.logoutEndPoint);

  app.get('/api/v2/import/microservice', _viewsController2.default.authenticateUser, _viewsController2.default.importMicroserviceEndPoint);

  app.post('/api/v2/get/element/instances/layouts', _buildController2.default.getElementInstancesLayoutsEndPoint);
  app.post('/api/v2/authoring/build/element/instance/create', _buildController2.default.createElementInstancesLayoutsEndPoint);
  app.post('/api/v2/authoring/user/track/delete', _buildController2.default.deleteElementInstancesLayoutsEndPoint);
  app.post('/api/v2/authoring/element/instance/layout/update', _buildController2.default.updateElementInstancesLayoutsEndPoint);

  app.post('/api/v2/authoring/get/element/module/layout', _publishingController2.default.getElementLayoutsEndPoint);
  app.post('/api/v2/authoring/element/module/create', _publishingController2.default.createElementLayoutsEndPoint);
  app.post('/api/v2/authoring/element/module/layout/update', _publishingController2.default.updateElementLayoutsEndPoint);
  app.get('/api/v2/authoring/element/module/delete/moduleid/:moduleId', _publishingController2.default.deleteElementLayoutsEndPoint);
  app.post('/api/v2/authoring/element/icon/upload/moduleid/:moduleId', _publishingController2.default.uploadElementIconEndPoint);
  app.post('/api/v2/authoring/fog/instances/layout/update', _fogController2.default.updateFogLayoutsEndPoint);

  app.post('/api/v2/authoring/fog/instances/list', _fogController2.default.getFogLayoutsEndPoint);
  app.post('/api/v2/authoring/fog/instance/delete', _fogController2.default.deleteFogLayoutsEndPoint);

  //generic error handler
  app.use(function (err, req, res, next) {
    _winstonLogs2.default.error('App crashed with error: ' + err);
    _winstonLogs2.default.error('App crashed with stack: ' + err.stack);
    console.log('App crashed with error: ' + err);
    console.log('App crashed with stack: ' + err.stack);
    res.status(500).send('Hmm, what you have encountered is unexpected. If problem persists, contact app provider.');
  });
  return app;
};

var startHttpServer = function startHttpServer(app, port) {
  _winstonLogs2.default.warn("| SSL not configured, starting HTTP server.|");

  console.log("------------------------------------------");
  console.log("| SSL not configured, starting HTTP server.|");
  console.log("------------------------------------------");

  app.listen(port, function onStart(err) {
    if (err) {
      console.log(err);
    }
    _winstonLogs2.default.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
    console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
  });
};

var startHttpsServer = function startHttpsServer(app, port, sslKey, sslCert, intermedKey) {
  try {
    var sslOptions = {
      key: _fs2.default.readFileSync(sslKey),
      cert: _fs2.default.readFileSync(sslCert),
      ca: _fs2.default.readFileSync(intermedKey),
      requestCert: true,
      rejectUnauthorized: false
    };
    //
    _https2.default.createServer(sslOptions, app).listen(port, function onStart(err) {
      if (err) {
        console.log(err);
      }
      _winstonLogs2.default.info('==> 🌎 HTTPS server listening on port %s. Open up https://localhost:%s/ in your browser.', port, port);
      console.info('==> 🌎 HTTPS server listening on port %s. Open up https://localhost:%s/ in your browser.', port, port);
    });
  } catch (e) {
    _winstonLogs2.default.error('Error: SSL-Key or SSL_CERT or INTERMEDIATE_CERT is either missing or invalid. Provide valid SSL configurations.');
    console.log('Error: SSL-Key or SSL_CERT or INTERMEDIATE_CERT is either missing or invalid. Provide valid SSL configurations.');
  }
};

exports.default = {
  startServer: startServer
};