const express = require("express")
    , bodyParser = require('body-parser')
    , youtubeSearch = require('./app/youtubeSearch')
    , logger = require('logops')  
    , port = 20116;
let domain = require('domain').create()

domain.on('error', function (error) {
    console.log(error)
})

const app = express()
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());


app.post('/v1/search.list', function (req, res) {
    domain.run(function () {
        try {
            youtubeSearch.search.list(res, youtubeSearch.getKey(), req.body.keyword, req.body.limit, req.body);
        } catch (e) {
            res.send();
        }
    })
})

app.post('/v1/search.channel', function (req, res) {
    domain.run(function () {
        youtubeSearch.target.channel(res, youtubeSearch.getKey(), req.body.id, req.body);
    })
})

app.post('/v1/search.playlist', function (req, res) {
    domain.run(function () {
        youtubeSearch.search.playlist(res, youtubeSearch.getKey(), req.body.keyword, req.body.limit, req.body);
    })
})

app.post('/v1/search.video', function (req, res) {
    domain.run(function () {
        youtubeSearch.search.video(res, youtubeSearch.getKey(), req.body.keyword, req.body.limit, req.body);
    })
})





app.post('/v1/search.channel/:id', function (req, res) {
    domain.run(function () {
        youtubeSearch.target.channel(res, youtubeSearch.getKey(), req.params.id, { part: req.body.part });
    })
})

app.post('/v1/search.playlist/:id', function (req, res) {
    domain.run(function () {        
        youtubeSearch.target.playlist(res, youtubeSearch.getKey(), req.params.id, { part: req.body.part });
    })
})

app.post('/v1/search.playlistitems/:id', function (req, res) {
    domain.run(function () {        
        youtubeSearch.target.playlistitems(res, youtubeSearch.getKey(), req.params.id, { part: req.body.part });
    })
})

app.post('/v1/search.video/:id', function (req, res) {
    domain.run(function () {        
        youtubeSearch.target.video(res, youtubeSearch.getKey(), req.params.id, { part: req.body.part });
    })
})



app.listen(port, () => {
    console.log("Server running on port " + port);
});
