"use strict";

var _path = _interopRequireDefault(require("path"));

var _https = _interopRequireDefault(require("https"));

var _express = _interopRequireDefault(require("express"));

var _ws = _interopRequireDefault(require("ws"));

var _httpProxyMiddleware = require("http-proxy-middleware");

var _utils = require("../utils");

var _httpsOptions = require("./httpsOptions");

var _devBuild = require("./devBuild");

var _logger = require("../logger");

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

// import webpack from 'webpack';
const options = (0, _utils.getOptions)(); // let args = process.argv.slice(3);

const httpsOptions = (0, _httpsOptions.httpsOptionsWithUserFriendlyError)(options);
const {
  app: {
    context,
    server
  }
} = options;
const {
  host,
  port,
  domain,
  disableContextURL,
  hasMock,
  mockPort
} = server;
const isCompatableHttp2 = Number(process.version.slice(1).split('.')[0]) >= 8;
const contextURL = disableContextURL ? '' : `/${context}`;
const serverUrl = (0, _utils.getServerURL)(server, 'htt' + 'ps');
const {
  zipname,
  cssSelectorZipPath,
  outputFolderLocation
} = (0, _devBuild.getPaths)();
const app = (0, _express.default)();

if (hasMock) {
  app.use(server.mockPrefix, (0, _httpProxyMiddleware.createProxyMiddleware)({
    target: 'ht' + `tp://localhost:${mockPort}`,
    changeOrigin: true
  }));
} // Nb@$#3NGscc


app.use(_express.default.json());
app.use(_express.default.urlencoded({
  extended: true
}));

const staticPart = _express.default.static(outputFolderLocation, {
  cacheControl: true,
  setHeaders: function (res) {
    if (options.app.enableDevCache) {
      res.setHeader('Cache-Control', 'public, max-age=604800');
    }

    res.setHeader('Access-Control-Allow-Origin', '*');
  }
});

if (contextURL === '') {
  app.use(staticPart);
} else {
  app.use(contextURL, staticPart);
}

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  next();
}).use(`${contextURL}/fonts`, _express.default.static(`${context}/fonts`));
app.use('/wms/*', (req, res) => {
  res.sendFile(_path.default.join(__dirname, '..', '..', 'templates', 'wms', 'index.html'));
});

const httpsServer = _https.default.createServer(httpsOptions, app);

if (httpsOptions) {
  const wss = new _ws.default.Server({
    server: httpsServer
  });
  let wsPool = [];
  wss.on('connection', ws => {
    wsPool.push(ws);
    ws.on('close', () => {
      wsPool = wsPool.filter(ws1 => ws1 !== ws);
    });
    ws.on('message', message => {
      (0, _utils.log)('received: %s', message);
    });
    ws.send('something');
  });
  app.post('/wmsmockapi', (req, res) => {
    wsPool.forEach(ws => {
      const {
        body
      } = req;

      try {
        ws.send(JSON.stringify(body));
      } catch (e) {
        (0, _utils.log)(e, body);
      }
    });
    res.send('success');
  });
} // let webpackCompilation;
// compiler.hooks.afterCompile.tap('ReactCLI', compilation => {
//   webpackCompilation = compilation;
// });


if (zipname) {
  app.use(`/zips/${zipname}.zip`, (req, res) => {
    res.download(_path.default.join(process.cwd(), cssSelectorZipPath), err => {
      if (err) {
        throw err;
      }

      (0, _logger.messageLogger)(`${zipname}.zip downloaded`);
    });
  });
  app.use('/zips/build.zip', (req, res) => {
    res.download(_path.default.join(process.cwd(), 'build.zip'), err => {
      if (err) {
        throw err;
      }

      (0, _logger.messageLogger)('build.zip downloaded');
    });
  });
}

if (contextURL) {
  app.use(contextURL, _express.default.static(context));
  app.use(`${contextURL}/*`, (req, res) => {
    // let indexHtml = webpackCompilation.assets['index.html'];
    res.sendFile(_path.default.join(outputFolderLocation, 'index.html')); // let indexHtml = webpackCompilation.assets['index.html'];
    // res.send(indexHtml && indexHtml.source());
  });
} else {
  app.use(_express.default.static(context));
  app.use('/*', _express.default.static(context));
}

if (httpsOptions) {
  httpsServer.listen(port, err => {
    if (err) {
      throw err;
    }

    (0, _utils.log)(`Listening at ${serverUrl}${contextURL}/`);
  });

  if (isCompatableHttp2) {
    const http2 = require('http2');

    const http2Server = http2.createSecureServer(httpsOptions); // eslint-disable-next-line no-unused-vars

    http2Server.on('stream', (stream, headers) => {
      stream.respond({
        'content-type': 'text/html',
        ':status': 200
      });
      stream.end('<h1>Hello World! <br>Working with http2</h1>');
    });
    const http2Port = Number(port) + 1;
    http2Server.listen(http2Port, err => {
      if (err) {
        throw err;
      }

      (0, _utils.log)(`Listening at ${(0, _utils.getServerURL)({
        host,
        domain,
        port: http2Port
      }, 'htt' + 'ps')}${contextURL}/`, 'http2 server');
    });
  } else {
    (0, _utils.log)('Your node version didn\'t adopted http2 support. Kindly update that to 8 LTS or above you can engage the http2');
  }
}

const httpPort = Number(port) + (isCompatableHttp2 ? 2 : 1);
app.listen(httpPort, err => {
  if (err) {
    throw err;
  }

  (0, _utils.log)(`Listening at ${(0, _utils.getServerURL)({
    host,
    domain,
    port: httpPort
  }, 'ht' + 'tp')}${contextURL}/`);
});