import thread
import time

from youtomb.explore.youtubeexplorer import YouTubeExplorer
import urllib
import youtomb.db

class SearchExplorer(YouTubeExplorer):
      def __init__(self, query, timeout_sec=600):
            YouTubeExplorer.__init__(self, timeout_sec, top_number=1000)
            self.query = query

      def get_gdata(self,start):
            uri = (('http://gdata.youtube.com/feeds/api/videos'
                    +'?vq=%s&start-index=%s&max-results=%s')
                   % (urllib.quote(self.query), start, min(25, 1000-start)))
            print 'getting %s' % uri
            return self.gdata_request(uri.replace('%','%%'))

      def get_name(self):
            return "SearchExplorer:%s" % self.query

if __name__=="__main__":
      db = youtomb.db.Database()
      query = 'SELECT query from queries'
      queries = [row['query'] for row in db.allrows(query)]


      for q in queries:                    # previously superbowl_queries
            tid = thread.start_new_thread(
                    lambda q: SearchExplorer(q).run(), (q,))
            # lambda is *horribly broken* in the presence of threads.  Sad.
            # Fortunately start_new_thread provides a workaround.
            print "started SearchExplorer thread %d on query %r" % (tid, q)
      while True:
            time.sleep(86400)
