const express = require('express');
const path = require('path');
const app = express();
const config = require('./config/app')
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require('compression');
const authChecker = require('./libs/auth/checker');

app.set('trust proxy', 1) //trust first proxy, get ip

// 设置视图引擎为EJS
app.set('view engine', 'ejs');

// 设置视图目录
app.set('views', path.join(__dirname, 'views'));

/**
 * Check should compress.
 */
function shouldCompress(req, res) {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
    return false
  }
  // fallback to standard filter function
  return compression.filter(req, res)
}

app.use(compression({
  filter: shouldCompress
}));


app.use(cookieParser());

app.use(express.static(config.STATIC_DIR));
app.use(express.static(path.join(__dirname, 'dist')));



app.use(session({
  store: new RedisStore({
    prefix: 'artsite_sess:'
  }),
  cookie: config.cookie,
  saveUninitialized: false,
  secret: 'MhxzKhl123.',
  resave: false,
  name: config.sessionName || sid,
}));


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));


app.use('/napi/web/auth', require('./routes/napi/web/auth'));
app.use('/napi/web/menu', authChecker.checkLogin, require('./routes/napi/web/menu'));
app.use('/napi/web/art', authChecker.checkLogin, require('./routes/napi/web/art'));
app.use('/napi/web/user', authChecker.checkLogin, require('./routes/napi/web/user'));
app.use('/napi/web/role', authChecker.checkLogin, require('./routes/napi/web/role'));


app.use('/thumbs/v1', require('./routes/res/thumbs'));

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


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



// catch 404 and forward to error handler
app.use(function (req, res) {
  // 设置状态码为404
  res.status(404);
  // res.sendFile(path.join(__dirname, '404.html'));
  res.render('404', { title: '404 Error', description: 'PAGE NOT FOUND' });
});


// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log("error:" + err);
  // render the error page
  res.status(err.status || 500);
  res.render('404', { title: '404 Error', description: 'PAGE NOT FOUND' });
});


// 启动服务器，监听6889端口
const PORT = process.env.PORT || 6889;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});