var proxy = require('express-http-proxy')
    , express = require('express')
    , cors = require('cors')
    , expressLogging = require('express-logging')
    , logger = require('logops')
    , httpsPort = 30443
    , port = 30001
    , supportedScopes = ['profile', 'status', 'avatar']
    , expiresIn = 3600
    , services = require('./app/services')
    , low = require('lowdb')
    , FileSync = require('lowdb/adapters/FileSync')
    , HttpStatus = require('http-status-codes')
    , https = require('https')
    , fs = require('fs');

const adapter = new FileSync(__dirname + '/storage/db.json')
const db = low(adapter)

db.get('authCodes').value()
    .forEach(codeData => {
        codeData.expiresDate = function () {
            var d = new Date();
            d.setDate(d.getDate() + 2);
            return d;
        }();
        services.authorizationService.saveAuthorizationCode(codeData, function (n, codeData) {
            // console.log(codeData)
        })
    });

var OAuthServer = require('simple-oauth-server'),
    oauthServer = new OAuthServer(
        services.clientService,
        services.tokenService,
        services.authorizationService,
        services.membershipService,
        expiresIn,
        supportedScopes
    );

function authorize(request, response) {
    // response.statusCode = 403;
    // response.json();
    // return true;
    console.log(request.query)
    oauthServer.authorizeRequest(request, request.query.account_id, function (error, authorizationResult) {
        if (error) {
            response.statusCode = 400;
            return response.end(JSON.stringify(error));
        }
        let code = require('url').parse(authorizationResult.redirectUri, true).query.code
        services.authCodes[request.query.client_id].code = code
        // var code = require('url').parse(authorizationResult.redirectUri, true).query.code;
        // response.statusCode = 302;
        // response.setHeader('Location', 'http://localhost:8080/oauth/token?client_id=1&grant_type=authorization_code&client_secret=kittens&code=' + code);

        response.end(JSON.stringify(authorizationResult));
    });
}

function grantToken(request, response) {
    oauthServer.grantAccessToken(request, function (error, token) {
        if (error) {
            console.log(error)
            response.statusCode = 400;
            return response.json(error);
        }
        response.json(token);
    });
}

function apiEndpoint(request, response) {
    console.log(oauthServer.validateAccessToken(request, function (error, validationResult) {
        if (error) {
            response.statusCode = 401;
            return response.json(error);
        }
        response.json(validationResult);
    }));
}

const proxyFilter = function (req, res) {
    return new Promise(function (resolve) {
        resolve(function () {
            if (req.headers.authorization) {
                var tokenData = services.getAccessTokens()[req.headers.authorization.split(' ').pop()];
                if (!tokenData || !tokenData.access_token) {
                    res.json({ code: HttpStatus.NOT_ACCEPTABLE })
                    return false;
                }
                if (tokenData.expiresDate < new Date()) {
                    res.json({ code: HttpStatus.NOT_ACCEPTABLE })
                    return false;
                }
                return true;
            }
            return false;
        }());
    });
}

const app = express()
app.use(expressLogging(logger));

app.use('/amazon', proxy('127.0.0.1:20111', {
    filter: proxyFilter
}));

app.use('/translate', proxy('127.0.0.1:20112', {
    filter: proxyFilter
}));

app.use('/coupang', proxy('127.0.0.1:20113', {
    filter: proxyFilter
}));

app.use('/task/coupang', proxy('127.0.0.1:20114', {
    filter: proxyFilter
}));

// app.use('/pinterest', proxy('127.0.0.1:20115'));
app.get('/pinterest/auth', (req, res) => {
    res.json({ok: 1})
});

app.use('/pinterest', proxy('127.0.0.1:20115', {
    filter: proxyFilter
}));


app.use('/youtube', proxy('127.0.0.1:20116', {
    filter: proxyFilter
}));


app.use('/spider', proxy('127.0.0.1:20117', {
    filter: proxyFilter
}));

app.use('/pang', proxy('127.0.0.1:20118', {
    filter: proxyFilter
}));


app.get('/oauth/authorize', authorize)

app.get('/oauth/token', grantToken)

app.get('/api/test', apiEndpoint)

var server = https.createServer({
    key: fs.readFileSync(__dirname + '/storage/cert/cert.key'),
    cert: fs.readFileSync(__dirname + '/storage/cert/cert.pem'),
    requestCert: false,
    rejectUnauthorized: false
}, app).listen(httpsPort, function(){
    console.log("server started at port " + httpsPort);
});

app.listen(port, function(){
    console.log("server started at port " + port);
});
