"use strict";

const express = require("express");
//const morgan = require('morgan');
const bodyParser = require("body-parser");
const compress = require("compression");
const responseTime = require("response-time");
const methodOverride = require("method-override");
const cors = require("cors");
const helmet = require("helmet");
const passport = require("passport");

const config = require("../config");
const router = require("./router");
const error = require("../middlewares/error");

const deviceCountryMiddleware = require("../middlewares/deviceCountry");

/**
 * Express instance
 * @public
 */
const app = express();

// request logging. dev: console | production: file
//app.use(morgan(logs));

// parse body params and attache them to req.body
app.use(bodyParser.json({ limit: "5mb" }));
app.use(
  bodyParser.urlencoded({
    limit: "5mb",
    extended: true,
  })
);

// set up the response-time middleware
app.use(responseTime());

// gzip compression
app.use(compress());

// lets you use HTTP verbs such as PUT or DELETE
// in places where the client doesn't support it
app.use(methodOverride());

// secure apps by setting various HTTP headers
app.use(helmet());

// enable CORS - Cross Origin Resource Sharing
//var allowedOrigins = ['http://localhost:8080', 'http://127.0.0.1:8080', 'https://adminapp2.loquedeverdadimporta.org'];

// enable CORS - Cross Origin Resource Sharing
app.use(
  cors({
    exposedHeaders: [
      "X-Country",
      "Content-Disposition",
      "Content-Type",
      "Content-Length",
      "X-Total-Count",
      "Pagination-Count",
      "Pagination-Page",
      "Pagination-Limit",
    ],
  })
);

/*app.use(cors({
    origin: function (origin, callback) {    
        // allow requests with no origin 
        // (like mobile apps or curl requests)
        return callback(null, true);

        if (!origin) {
            return callback(null, true);
        }

        console.log('origin =>', origin);

        if (allowedOrigins.indexOf(origin) === -1) {
            var msg = 'The CORS policy for this site does not ' +
                'allow access from the specified Origin.';
            return callback(new Error(msg), false);
        } 

        return callback(null, true);
    }
}));*/

/*app.use(cors({
    origin: '*',
    exposeHeaders: [
        "WWW-Authenticate",
        "Server-Authorization",
        "Content-Disposition", 
        "Content-Type",         
        "Content-Length"
    ],
    maxAge: 31536000,
    credentials: true,
    allowMethods: [
        "GET",
        "POST",
        "PUT",
        "PATCH",
        "DELETE",
        "OPTIONS",
        "HEAD"
    ],
    allowHeaders: [
        "Access-Control-Allow-Origin",
        "Content-Type",
        "X-CSRF-Token", 
        "X-Requested-With", 
        "Accept", 
        "Accept-Version",
        "Content-Length", 
        "Content-MD5", 
        "Date", 
        "X-Api-Version", 
        "X-File-Name",
        "Authorization",
        "X-Frame-Options",
        "Origin",
    ],
}));*/

app.use(deviceCountryMiddleware.middleware());

// Access validator
app.use(passport.initialize());
require("./passport");

// APIDOC
app.use("/doc", express.static("apidoc"));

// Set routes
app.use("/api", router());

// if error is not an instanceOf APIError, convert it.
app.use(error.converter);

// catch 404 and forward to error handler
app.use(error.notFound);

// error handler, send stacktrace only during development
app.use(error.handler);

module.exports = app;
