const path = require("path"),
    express = require('express'),
    app = express(),
    server = require('http'),
    favicon = require("serve-favicon"),
    fs = require('fs'),
    chalk = require("chalk"),
    bodyParser=require('body-parser');

const httpServer = class httpServer {
    constructor({ config,thirdPartyPlayer }) {
        this.thirdPartyPlayer=thirdPartyPlayer;
        this.config = config;
        this.webPath = path.resolve(process.cwd(), 'smg', 'web-client-dist');
        this.port = this.config.Settings.ServicePort || process.env.PORT;
        this.server = server.createServer(app);
    }

    async init() {
        // CORS
        try {
            app.use(function(req, res, next) {
                res.header("Access-Control-Allow-Origin", "*");
                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                next();
            });
        } catch (e) {
            console.log(`cant use cors, err: ${e}`);
        }
        // Favicon
        try {
            app.use(favicon(path.join(this.webPath, '/images/favicon.png')));
        } catch (e) {
            console.log(chalk.white.bgRed.bold("Error while accessing favicon\n" + e));
        }

        // Static content
        try {
            app.use(express.static(this.webPath));
        } catch (e) {
            console.log(chalk.white.bgRed.bold("Error accessing public folder\n" + e));
        }

        try{
            app.use(bodyParser.urlencoded({ extended: true }));
            app.use(bodyParser.json({type:'application/json'}));
        }catch (e){
            console.log(chalk.red('cant use bodyParser'));
        }

        app.post('/api', async (req, res, next) => {
            //  req.url.
            if (this.thirdPartyPlayer){
              let response= await this.thirdPartyPlayer.requestParser(req.body)
                  res.statusCode=200;
                  return res.json(response);
                  res.end();
            }
        });


        // Files
        app.get('/files/*', (req, res, next) => {

            let options = {
                root: path.join(process.cwd(), 'files/', path.dirname(req.params[0])),
                dotfiles: 'deny',
                headers: {
                    'x-timestamp': Date.now(),
                    'x-sent': true,
                    'Cache-Control': 'public, must-revalidate, max-age=0',
                    'content-type': 'audio/mp3'
                }
            };

            let fileName = path.basename(req.params[0]);
            res.sendFile(fileName, options, function (err) {
                if (err) {
                    next(err);
                } else {
                    console.log('Sent:', fileName);
                }
            });

        });

        // File download
        app.get('/download/:fileName', (req, res) => {

            let file = path.join(process.cwd(), '/files/', req.params.fileName);

            fs.exists(file, (e) => {
                if (e) {
                    res.sendFile(file);
                } else {
                    res.redirect('/');
                }
            });
        })

        // 500 Error
        app.use(function (err, req, res, next) {
            if (err) {
                console.log('Error', err);
            } else {
                console.log('404')
            }
        });
        // Server listening
        this.server.listen(this.port, () => {
            console.log(chalk.white.bgBlue.bold(`HTTP Server Running:${this.port}`))
        });

    }

}

module.exports = httpServer;
