const express = require("express")
    , { exec } = require('child_process')
    , cron = require('node-cron')
    , expressLogging = require('express-logging')
    , logger = require('logops')
    , path = require('path')
    , service = require('./src/Service')
    , port = 20117;

var app = express();
app.use(express.json())
app.use(expressLogging(logger));

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

app.get('/token', (req, res) => {
    service.call((output) => {
        res.json(output)
    }, 'key')
})

app.get('/news/chtoday', (req, res) => {
    service.getChtodayNews().then(body => res.json(body))
})

app.get('/podbbang', (req, res) => {
    service.getPodbbangChristianRecent(req.body).then(body => { res.send(body) });
})

app.get('/youtube/channel', (req, res) => {
    service.getChannelVideo();
    res.send({ code: 200 })
})

app.get('/youtube/playlist', (req, res) => {
    service.getPlaylistVideo()
    res.send({ code: 200 })
})

app.put('/youtube/video/check/:id', (req, res) => {
    service.checkVideoDeleted(req, res)
})

app.get('/youtube/stats', (req, res) => {
    service.youtubeVideoStats(req.query.loops);
    res.send({ code: 200 })
})

app.get('/youtube/channel/:id', (req, res) => {
	console.log(req.params.id)
	console.log(req.params.id)
    service.getChannelVideo(req.params.id);
    res.send({ code: 200 })
})

app.get('/naver/place/church/:page', (req, res) => {
    service.getNaverPlaceChurch(req.params).then(localRes => {
        res.send(localRes)
    })
})

cron.schedule('0,20,40 * * * *', () => {
    service.getChtodayNews().then(body => logger.info('Chtoday new feed successfully : ', body))
})
cron.schedule('0 1,7,13,19,0  * * *', () => {
    service.getPodbbangChristianRecent().then(body => console.log('Podbbang crawling successfully : ', body))
})
cron.schedule('0 1,7,13,19,0 * * *', () => {
    service.getChannelVideo()
    service.getPlaylistVideo()
})
cron.schedule('30 1,7,13,19,0 * * *', () => {
    service.youtubeVideoStats();
})
cron.schedule('1 0 * * *', () => {
    exec(path.dirname(__dirname) + '/.log.sh', function (err, stdout, stderr) {
        console.log(err, stdout, stderr);
    })
})


process.on('unhandledRejection', e => {
    logger.info('unhandledRejection', e.message);
})