const newsFeed = require('./NewsFeed'),
    localClient = require('./LocalClient'),
    youtubeClient = require("./YoutubeServiceClient"),
    targetChannels = require("./targetChannels"),
    podbbang = require("./Podbbang"),
    naver = require('./Naver'),
    logger = require('logops');


class Service {

    constructor() {
        this.init()
    }

    shuffle(a) {
        for (let i = a.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [a[i], a[j]] = [a[j], a[i]];
        }
        return a;
    }

    async init() {
        // await localClient.getChannel().then(res => {
        //     targetChannels.map(targetChannel => {
        //         targetChannel.youtubeChannels = []
        //         res.data.map(cm => {
        //             if (cm.CategoryId == targetChannel.cmCategoryId) {
        //                 targetChannel.youtubeChannels.push({
        //                     title: cm.EditorName,
        //                     url: cm.YtChannelId,
        //                     editor: cm.EditorId
        //                 })
        //             }
        //         })
        //     })
        // })
        // console.log(JSON.stringify(targetChannels))
        // this.targetChannels = targetChannels
    }

    getNaverPlaceChurch(params) {
        if (params.page == 'auto' || params.auto == true) {
            params.page = params.page == 'auto' ? 0 : params.page
            if (86518 > params.page * 30 + 50000) {
                return naver.place.getData({ start: params.page * 30 + 50000 }).then(body => localClient.saveNaverPlace(body)).then(localRes => {
                    params.page++
                        params.auto = true
                    this.getNaverPlaceChurch(params)
                    return localRes
                })
            }
        } else {
            return naver.place.getData({ start: page * 30 + 1 }).then(body => localClient.saveNaverPlace(body))
        }
    }

    getChtodayNews() {
        return localClient.getToken().then(body => newsFeed.ct.getLatest(body.token).then(body => localClient.saveChtodayNews(body)))
    }

    youtubeVideoStats(loops = 250) {
        for (var i = 0; i < loops; i++) {
            localClient.getYoutubeVideo({
                "offset": i * 10,
                "limit": 10
            }).then(data => {
                if (data.data.length) {
                    let promises = []
                    data.data.map((v, k) => {
                        promises.push(youtubeClient.getVideo(v.VideoId, {
                            "part": "statistics"
                        }))
                    })
                    Promise.all(promises).then(data => {
                        let yt = { deleted: [], videos: [] }
                        data.map((body, k) => {
                            if (body.code == 200) {
                                yt.videos.push({
                                    VideoId: body.data.id,
                                    Likes: body.data.raw.statistics.likeCount,
                                    Views: body.data.raw.statistics.viewCount,
                                    Comments: body.data.raw.statistics.commentCount,
                                    Subscribes: body.data.raw.statistics.favoriteCount
                                })
                            } else {
                                logger.info(body.message)
                                if (body.code == 404) {
                                    yt.deleted.push({ VideoId: body.data.id })
                                }
                            }
                        })
                        return yt;
                    }).then(yt => {
                        localClient.saveYoutubeVideoCuration({ action: 'update', videos: yt.videos })
                            .then(body => console.log('Update video result :', body))
                        if (yt.deleted.length) {
                            localClient.deleteYoutubeVideoCuration({ action: 'delete', videos: yt.deleted })
                                .then(body => console.log('Delete video result :', body))
                        }
                    })
                }
            })
        }
    }

    getVideoByChannelId(channel) {
        if (channel.indexOf('UC') > -1) {
            youtubeClient.getRecentVideo({
                "limit": 20,
                "order": "date",
                "channelId": channel
            }).then(body => {
                res.json(body)
            })
        } else {
            // channel user custom name
            youtubeClient.getChannel({
                "forUsername": channel
            }).then(body => {
                youtubeClient.getRecentVideo({
                    "limit": 20,
                    "order": "date",
                    "channelId": body.id
                }).then(body => {
                    res.json(body)
                })
            });
        }
    }

    checkVideoDeleted(req, res) {
        youtubeClient.getVideo(req.params.id, {
            "part": "statistics"
        }).then(data => {
            if (data.code == 403) {
                res.json({ code: 200, message: 'Daily Limit Exceeded' })
            } else if (data.code == 404) {
                localClient.deleteYoutubeVideoCuration({ action: 'delete', videos: [{ VideoId: req.params.id }] }).then(body => res.send(body))
            } else res.json({ code: 200, data: data })
        })
    }

    getPlaylistVideo() {
        let videoCount = 0;
        targetChannels.forEach((category) => {
            category.youtubeChannels.forEach((yt) => {
                let ytChannel = yt.url.split('/').pop()
                if (ytChannel.indexOf('playlist') > -1) {
                    let ytPlaylist = ytChannel.split('=').pop()
                    youtubeClient.getPlaylistItem(ytPlaylist, {
                        "part": "snippet",
                        "maxResults": 100
                    }).then(body => {
                        if (!body.code) {
                            let data = {
                                categoryTitle: yt.subcat,
                                videos: body
                            }
                            videoCount = videoCount + body.length
                            localClient.saveYoutubeVideoCuration(data)
                        }
                    })
                }
            })
        })
    }

    getChannelVideo(singleChannel) {
        let videoCount = 0;
        targetChannels.forEach((category) => {
            this.shuffle(category.youtubeChannels).forEach((yt) => {
                let ytChannel = yt.url.split('/').pop()
                if (ytChannel.indexOf('UC') > -1) {
                    if (typeof singleChannel == 'undefined' || (typeof singleChannel != 'undefined' && ytChannel == singleChannel)) {
                        this.requestYtAndSave(category, yt, ytChannel)
                    }
                } else {
                    youtubeClient.getChannel({
                        "forUsername": ytChannel
                    }).then(body => {
                        if (body.id) {
                            if (typeof singleChannel == 'undefined' || (typeof singleChannel != 'undefined' && body.id == singleChannel)) {
                                this.requestYtAndSave(category, yt, body.id)
                            }
                        }
                    });
                }
            })
        })
    }

    requestYtAndSave(category, yt, channelId) {
        youtubeClient.getRecentVideo({
            limit: 120,
            order: "date",
            // videoEmbeddable: true,
            channelId: channelId
        }).then(channelVideos => {
            if (Array.isArray(channelVideos)) {
                let promises = []
                channelVideos.map((v, k) => {
                    promises.push(youtubeClient.getVideo(v.id, {
                        "part": "snippet"
                    }))
                })
                Promise.all(promises).then(data => {
                    data.map((body, k) => {
                        if (body.code == 200) {
                            for (let j in channelVideos) {
                                if (body.data.id == channelVideos[j].id) {
                                    channelVideos[j].description = body.data.description;
                                }
                            }
                        }
                    })
                    return channelVideos
                }).then(channelVideos => {
                    localClient.saveYoutubeVideo({
                        categoryId: category.cmCategoryId,
                        categoryTitle: category.cmCategoryTitle,
                        editorId: yt.editor,
                        videos: channelVideos
                    }).then(body => logger.info(body))
                })
            } else {
                console.log('No recent videos from youtube API with ' + JSON.stringify(yt))
                console.log('Instead received data is ' + channelVideos)
            }
        })
    }

    getPodbbangChristianRecent(params, scrolls = 100) {
        params = params ? params : {
            "timeout": 3600,
            "timezone": "Asia/Seoul",
            "lua_source": "function main(a,b)a.images_enabled=false;a:go('http://www.podbbang.com/categories/1033?sort=update')for c=0," + scrolls + ",1 do a.scroll_position={y=200000}a:wait(1.5)end;a:set_result_content_type('text/html; charset=utf-8')return a:html()end"
        }
        return podbbang.getLatest(params).then(body => localClient.savePodbbangStation(body))
    }

    responseKey(callback) {
        return (err, stdout, stderr) => {
            callback(JSON.parse(stdout))
        }
    }


}


module.exports = new Service