#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = "helljump"
key = "AIzaSyCseSy2EJgIIjqCEnSKT8PBgDoSqCq1w08"

import logging
from grab import Grab
import json
from urllib import urlencode


log = logging.getLogger(__name__)


class YouTube(object):

    URL = "https://gdata.youtube.com/feeds/api/videos"
    PAGE = 10

    def __init__(self, queries, amount=1000, apikey=None, stopwords=None, minlen=10, timeq=None):
        self.queries = queries
        self.timeq = timeq or 'all_time'
        self.results = 0
        self.query = None
        self.amount = amount
        self.stopwords = stopwords or [u'хуй', u'пизд', u'кредит']
        self.minlen = minlen
        self.g = Grab(
            headers={"X-GData-Key": "key=" + (apikey or key)},
            hammer_mode=True
            )

    def get_items(self):
        for query in self.queries:
            if len(query.strip()) == 0:
                continue
            assert isinstance(query, unicode)
            self.query = query
            start_index = 1
            params = {"q": query.encode('utf-8'), "max-results": YouTube.PAGE, "v": "2", "alt": "jsonc",
                "time": self.timeq}
            amount = self.amount
            while amount:
                params["start-index"] = start_index  # индекс видео, не страницы!
                rc = self.g.go(YouTube.URL + "?" + urlencode(params))
                egg = json.loads(rc.unicode_body())
                if "error" in egg:
                    raise Exception(egg["error"]["message"])
                data = egg["data"]
                self.results = int(data["totalItems"])
                if "items" not in data:
                    break
                for item in data["items"]:
                    if self._swmatch(item["title"]) or self._swmatch(item["description"]):
                        continue
                    item["query"] = query
                    yield(item)
                    amount -= 1
                    if not amount:
                        break
                start_index = int(data["startIndex"]) + YouTube.PAGE
                if start_index > self.results:
                    break

    def _swmatch(self, text, minlen=1):
        text = text.lower()
        for word in self.stopwords:
            if text and word and text.find(word) != -1:
                #print ">>>", word.encode("UTF-8")
                return True
        if len(text) < minlen:
            return True
        return False

    '''
    def get_comments(self, yid):
        url = YouTube.URL + "/" + yid + "/comments"
        #print "-->", url
        params = {"v": "2", "alt": "json"}
        rc = self._get(url, params=params, headers=self.headers, verify=False)
        if rc.status_code != 200:
            raise Exception(str(rc))
        egg = rc.json()
        if "error" in egg:
            raise Exception(egg["error"]["message"])
        if "entry" not in egg["feed"]:
            return []
        spam = [entry for entry in egg["feed"]["entry"]
            if not self._swmatch(entry["content"]["$t"], self.minlen)]
        return spam
    '''


def main():
    yt = YouTube([u"как играть на гитаре"], 30)
    for item in yt.get_items():
        print item["id"],  # , item["title"].encode("cp866", "replace"), item["description"]
        print item["thumbnail"]["hqDefault"]


if __name__ == '__main__':
    main()
