from channelguide import init
init.init_external_libraries()
from channelguide import db, util
from channelguide.guide.models import Channel, Category
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.syndication.feeds import Feed

class ChannelsFeed(Feed):
    title_template = "feeds/channel_title.html"
    description_template = "feeds/channel_description.html"

class NewChannelsFeed(ChannelsFeed):
    title = 'Newest Channels'
    link = "/channels/recent"
    description = "The newest channels on the Miro Guide."

    def items(self):
        connection = db.connect()
        query = Channel.query_new().limit(10)
        items = query.execute(connection)
        connection.close()
        return items

class CategoriesFeed(ChannelsFeed):

    def get_object(self, bits):
        connection = db.connect()
        if len(bits) != 1:
            raise ObjectDoesNotExist
        print 'getting object for', bits
        try:
            obj = util.get_object_or_404_by_name(connection, Category, bits[0])
        except Exception:
            raise ObjectDoesNotExist
        connection.close()
        return obj

    def title(self, obj):
        return 'Newest Channels in %s' % obj.name.encode('utf8')

    def link(self, obj):
        return obj.get_url()

    def description(self, obj):
        return 'The newest %u channels in the Miro Guide' % obj.name.encode('utf8')

    def items(self, obj):
        connection = db.connect()
        query = Channel.query_new().join('categories').limit(10)
        query.joins['categories'].where(id=obj.id)
        items = query.execute(connection)
        for item in items:
            print repr(item.name), repr(item.description)
        connection.close()
        return items


@@ -574,32 +574,121 @@
     
-connection = db.connect(
+import logging%0A        logging.info(self.title_template_name)%0A        logging.info(self.description_template_name
 )%0A  
@@ -753,32 +753,45 @@
 = query.execute(
+self.request.
 connection)%0A    
@@ -794,33 +794,40 @@
         
-connection.close(
+logging.info(repr(items)
 )%0A      
@@ -915,42 +915,8 @@
 s):%0A
-        connection = db.connect()%0A
     
@@ -979,49 +979,8 @@
 ist%0A
-        print 'getting object for', bits%0A
     
@@ -1041,19 +1041,52 @@
 ame(
-connection,
+self.request.connection,%0A                   
  Cat
@@ -1168,35 +1168,8 @@
 ist%0A
-        connection.close()%0A
     
@@ -1391,17 +1391,17 @@
 newest %25
-u
+s
  channel
@@ -1478,42 +1478,8 @@
 j):%0A
-        connection = db.connect()%0A
     
@@ -1624,113 +1624,21 @@
 ute(
-connection)%0A        for item in items:%0A            print repr(item.name), repr(item.description)%0A        
+self.request.
 conn
@@ -1647,15 +1647,8 @@
 tion
-.close(
 )%0A  

add some logging