const express = require('express');
const http = require('http');
const router = express.Router();
const app = express();
const fs = require('fs');
var bodyParser = require("body-parser");
var request = require("request");
const edurouter = require("./pbl");
const certificate = require("./certificate");
var path = require("path");

var port = "7333"; // set our port


process.env.NODE_ENV = 'dev';
// main.use((req, res, next) => {
//     var deviceAgent = req.headers['user-agent'].toLowerCase();
//     var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
//     if (agentID)
//         req.ismobile = true;
//     else
//         req.ismobile = false;
//     next();
// });
app.use(bodyParser.urlencoded({ extended: true, limit: "3mb" }));
app.use(bodyParser.json({ limit: "3mb" }));


//暂时全跨域
app.use(function (req, res, next) {
	///var allowedOrigins = [config.local.origin,'http://cocorobo.hk','http://www.cocorobo.hk','https://cocorobo.hk','http://cloud.cocorobo.hk','https://cloud.cocorobo.hk'];
	var origin = req.headers.origin || "*";
	//if(allowedOrigins.indexOf(origin) > -1){
	res.setHeader("Access-Control-Allow-Origin", origin);
	//}
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header(
		"Access-Control-Allow-Headers",
		"Origin, X-Requested-With, Content-Type, Accept"
	);
	res.header("Access-Control-Allow-Credentials", true);
	//修改程序信息与版本
	res.header("X-Powered-By", " 3.2.1");
	//内容类型：如果是post请求必须指定这个属性
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});

/*
app.use(cors({
    origin:[`http:${config.local.origin}`,'http://www.cocorobo.hk','https://cocorobo.hk','http://cloud.cocorobo.hk','https://cloud.cocorobo.hk'],
    methods:['GET','POST','PUT','DELETE'],
    credentials: true // enable set cookie
}));
*/

let verifToken = require("./token.js");
app.use(verifToken);


// all of our routes will be prefixed with /api
app.use("/api/pbl", edurouter);
app.use("/api/pbl", certificate);
// 设置静态目录，带虚拟前缀
app.use('/static', express.static(path.join(__dirname, 'static')));
// app.use('/game', game);

app.all("/download", function (req, res, next) {
	//req.body.url = "https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E4%B8%8B%E8%BD%BD%20%284%29.doc";
	request(
		{
			url: req.body.url,
			method: "GET",
			encoding: null,
			headers: {
				"Accept-Encoding": "gzip, deflate",
			},
		},
		function (error, response, body) {
			if (!error && response.statusCode == 200) {
				res.setHeader("Content-Type", "application/force-download");
				res.setHeader(
					"Content-Disposition",
					"attachment; filename=" + path.basename(req.body.url)
				);
				res.setHeader("Content-Length", body.length);
				res.send(body);
			}
		}
	);
});

// START THE SERVER
// =============================================================================
app.listen(port);
console.log("app happens on port " + port);
app.use(function (req, res, next) {

    res.send("404 Not Found");
});


module.exports = app;