const express = require('express')
// const session = require('express-session')
const history = require('connect-history-api-fallback')
const path = require('path')
const app = express()

// let sessionOpts = {
//   // 设置密钥
//   secret: 'a cool secret',
//   // Forces the session to be saved back to the session store
//   resave: true,
//   // Forces a session that is "uninitialized" to be saved to the store.
//   saveUninitialized: true,
//   // 设置会话cookie名, 默认是connect.sid
//   key: '_STOKEN',
//   // If secure is set to true, and you access your site over HTTP, the cookie will not be set.
//   cookie: { maxAge: 1000 * 60 * 60 * 2, secure: false }
// }

app.set('port', process.env.SERVER_PORT || 3000)

// app.use(session(sessionOpts))

app.use('/', require('./routes'))

app.use(history({ verbose: false, index: '/' }))
app.get('/', (req, res) => {
  /* 增加 限定条件，如果是 e-learning2 子域名，那么 referer 为指定 域名 否则不能打开 */
  if (/^e-learning2\./.test(req.headers.host)) {
    if (/(sofia\.tenant\.ezijing)|(sofia-x\.ezijing)|(course\.ezijing)|(course3\.ezijing)/.test(req.headers.referer)) {
      let opts = { path: '/', domain: '.ezijing.com', expires: null, httpOnly: true }
      res.cookie('_stoken', req.query.stoken, opts)
      res.sendFile(path.join(__dirname, '../client-dist/index.html'))
    } else {
      res.send('当前页面打开方式不对')
    }
  } else {
    res.clearCookie('_stoken', { path: '/', domain: '.ezijing.com' })
    res.sendFile(path.join(__dirname, '../client-dist/index.html'))
  }
})
app.use(express.static(path.join(__dirname, '../client-dist')))

app.set('trust proxy', true)
/* 开启服务 */
global.SocketServer = app.listen(app.get('port'), function () {
  console.log('Express server 🌎  listening on：http://localhost:' + app.get('port'))
})
