# -*- coding: utf-8 -*-
import logging
import json
import urllib
import os
import sys
from threading import Thread

from twisted.internet import reactor
import requests
from bs4 import BeautifulSoup as bs4
from soupy import Soupy, Q

requests.packages.urllib3.disable_warnings()

log = logging.getLogger('giantbomb')
t = None
videos = {}
getvids_callLater = None
bot = None
config = None
useragent = None

VIDEO_NAMES = {'ql': 'Quick Look', 'sub': 'Premium Video', 'feature': 'Feature', 'bombastica': 'Encyclopedia Bombastica',
                'event': 'Event Video', 'unfinished': 'Unfinished', 'er': 'Endurance Run'}
VIDEO_CODES = {'ql': '3', 'sub': '10', 'feature': '8', 'bombastica': '12', 'event': '6', 'er': '5', 'unfinished': '13'}
VIDEO_URL = "http://www.giantbomb.com/api/videos/?api_key=%s&format=json&limit=1&filter=video_categories:%s"
PODCAST_NAMES = {'premcast': 'Premium Podcast', 'presents': 'GB Presents'}
PODCAST_URLS = {'premcast': 'http://www.giantbomb.com/podcasts/premium/', 'presents': 'http://www.giantbomb.com/podcasts/giant-bomb-presents/'}
CHANNEL = "#giantbomb"

def event_signedon(bot):
    global getvids_callLater, videos

    with open(os.path.join(sys.path[0], 'modules', 'module_giantbomb_conf.json')) as datafile:
        videos = json.load(datafile)
    log.info("Loaded cached video names")

    if getvids_callLater != None:
        log.info("Stopping previous scraping thread")
        getvids_callLater.cancel()
    rotator_getvids(bot, 500)

def handle_privmsg(bot, user, channel, cmd):
    global videos
    msg = cmd[1:]
    if(user == channel):
        if(msg == "startgb"):
            bot.say(channel, "GB scraper started!")
            with open(os.path.join(sys.path[0], 'modules', 'module_giantbomb_conf.json')) as datafile:
                videos = json.load(datafile)
            log.info("Loaded cached video names")
            if getvids_callLater != None:
                log.info("Stopping previous scraping thread")
                getvids_callLater.cancel()
            rotator_getvids(bot, 500)


def init(botref):
    global config, bot, apikey, bearer, useragent
    bot = botref
    config = bot.config.get("module_giantbomb", {})
    apikey = config.get("apikey")
    twitconfig = bot.config.get("module_urltitle", {})
    bearer = twitconfig.get('twitter_bearer')
    useragent = bot.config.get("nick")

def finalize():
    if getvids_callLater is not None:
        try:
            log.info("Stopping previous scraping thread")
            getvids_callLater.cancel()
        except Exception, e:
            log.error("Exception occurred stopping scraping thread")
            log.error(e)


def command_gb(bot, user, channel, args):
    """.gb upcoming - Returns any posted upcoming items at GiantBomb.com (it's a website about video games)"""
    global videos
    if args:
        cmds = args.split()
        subcommand = cmds[0]
        if subcommand == "upcoming":
            page = bs4(urllib.urlopen("http://www.giantbomb.com/"))
            upcoming = page.find("dl", {"class": "promo-upcoming"})
            if not upcoming:
                bot.say(channel, "No items on the upcoming list! Alert @GiantBombStats!")
            slots = upcoming.find_all("dd")
            bot.say(channel, "%d Upcoming Items (times in EST):" % len(slots))
            for slot in slots: