#
# etsyuserinfo.py - Get information on Etsy users.
# Written by Nick A. Rusnov, 2007
#

import urllib
from xml.dom.minidom import parse
import time

def domGetChildWT(dom, element_name):
    if dom.getElementsByTagName(element_name):
        if dom.getElementsByTagName(element_name)[0].firstChild:
            return dom.getElementsByTagName(element_name)[0].firstChild.wholeText
    return ''

class EtsyUserFavorites:
    """This is a simple class to gather information on an Etsy user's favorites."""    

    def __init__(self, userId=0):
        self._favorite_shops = list()
        self._favorite_items = list()
        self.user_id = userId

    def _xml_get(self):
        f = urllib.urlopen("http://api.etsy.com/feeds/xml_favorites.php?user_id=%d" % int(self.user_id))
        dom = parse(f)
        f.close()

        listings = dom.getElementsByTagName('root')[0].getElementsByTagName('favorite_listings')[0].getElementsByTagName('listing')
        shops = dom.getElementsByTagName('root')[0].getElementsByTagName('favorite_shops')[0].getElementsByTagName('user')

        for i in shops:
            shop_id = i.getAttribute('id')
            shop_user_name = domGetChildWT(i, 'user_name')
            shop_image_id = domGetChildWT(i, 'image_id')
            shop_image_path = domGetChildWT(i, 'image_path')
            shop_last_update = domGetChildWT(i, 'last_updated')
            self._favorite_shops.append(EtsyFavoriteShop(shop_id, shop_user_name, shop_image_id, shop_image_path))

        for i in listings:
            listing_id = i.getAttribute('id')
            listing_image_id = domGetChildWT(i, 'image_id')
            listing_image_path = domGetChildWT(i, 'image_path')
            listing_date = domGetChildWT(i, 'listing_date')
            mark_date = domGetChildWT(i, 'marked_date')
            self._favorite_items.append(EtsyFavoriteListing(listing_id, listing_image_id, listing_image_path, listing_date, mark_date))
        
    def get_items(self):
        if not self._favorite_items:
            self._xml_get()

        for i in self._favorite_items:
            yield i
            
    def get_shops(self):
        if not self._favorite_shops:
            self._xml_get()

        for i in self._favorite_shops:
            yield i


    items = property(get_items)
    shops = property(get_shops)

    def __repr__(self):
        return '<EtsyUserFavorites id:%i>' % (self.user_id,)

class EtsyImage:
    def __init__(self, image_id, image_path, im_prefix='il'):
        self.image_id = image_id
        self.image_path = image_path

        self.large = self.image_path + im_prefix + '_430xN.%s.jpg' % self.image_id
        self.small = self.image_path + im_prefix + '_155x125.%s.jpg' % self.image_id
        self.thumb = self.image_path + im_prefix + '_75x75.%s.jpg' % self.image_id
        self.smallthumb = self.image_path + im_prefix + '_50x50.%s.jpg' % self.image_id

        
class EtsyFavoriteShop(EtsyImage):
    def __init__(self, user_id, user_name, image_id, image_path):
        EtsyImage.__init__(self, image_id, image_path, 'iusa')
        self.id = user_id
        self.name = user_name

        self.shop_url = 'http://www.etsy.com/shop.php?user_id=' + user_id
        self.profile_url = 'http://www.etsy.com/profile.php?user_id=' + user_id

    def __repr__(self):
        return '<EtsyFavoriteShop id:%s>' % (self.id,)
    
class EtsyListing(EtsyImage):
    def __init__(self, listing_id, image_id, image_path, listing_date):
        EtsyImage.__init__(self, image_id, image_path)
        self.id = listing_id
        self.listing_date = listing_date

        self.url = 'http://www.etsy.com/view_listing.php?listing_id=' + listing_id

    def __repr__(self):
        return '<EtsyListing id:%s>' % (self.id,)

class EtsyFavoriteListing(EtsyListing):
    def __init__(self, listing_id, image_id, image_path, listing_date, mark_date):
        EtsyListing.__init__(self, listing_id, image_id, image_path, listing_date)
        self.mark_date = mark_date

    def __repr__(self):
        return '<EtsyFavoriteListing id:%s>' % (self.id,)


class EtsyUserInfo:
    """This is a simple class, which, given a user ID will retrieve the profile using Etsy's XML API."""    
    def __init__(self, user_id):
        user_name = ''
        is_active = False
        is_seller = False
        city = ''
        country = ''
        image_id = ''
        image_path = ''
        shop_name = ''
        title = ''
        text = ''
        last_updated = ''
        create_date = ''
        feedback_percentage = '0%'
        feedback_total = 0
        bio = ''
        location = ''

        self.user_id = int(user_id)
        # we'll assume the url is available and the XML parses okay...
        f = urllib.urlopen("http://api.etsy.com/feeds/xml_user_details.php?id=%d" % int(user_id))
        dom = parse(f)
        f.close()

        # load some interesting information from the document.
        # this is not a pretty way to do this; meh, dom.
        usrs = dom.getElementsByTagName('root')[0].getElementsByTagName('user')
        # look through the user list and find the proper one; well, really ensure that the user element
        # that is likely alone in the list is the correct one.
        for usr in usrs:
            if usr.hasAttribute('id') and int(usr.getAttribute('id')) == int(user_id):
                # we found the proper user
                for tag in usr.childNodes:
                    # gather up all the information about the user
                    if (tag.nodeType == tag.ELEMENT_NODE):
                        # we'll just store each 'simple' value on this object:
                        if tag.nodeName != 'listings':
                            if tag.firstChild:
                                val = tag.firstChild.wholeText
                                # these types should not be stripped
                                if not tag.nodeName in ('bio','text'):
                                    val = val.strip()
                                # these types map to bools
                                if tag.nodeName in ('is_active', 'is_seller'):
                                    if val == 'false':
                                        val = False
                                    else:
                                        val = True
                                # percentage
                                elif tag.nodeName == 'feedback_percentage':
                                    val = val + '%'
                                # dates
                                elif tag.nodeName in ('last_update','create_date'):
                                    val = time.ctime(float(val))

                                # store it
                                self.__dict__[str(tag.nodeName)] = val
                                    
                        else:
                            # decoding the listings would happen here. 
                            continue



    
    def __repr__(self):
        return '<EtsyUserInfo id:%i name:%s>' % (self.user_id, self.user_name)


if __name__ == '__main__':
    euf = EtsyUserFavorites('54484')
    for i in euf.shops:
        print i.thumb

# if __name__ == '__main__':
#     userIds = [42346, 77290, 729]
#     cities = dict()

#     for uid in userIds:
#         user = EtsyUserInfo(uid)
#         if not cities.has_key(user.city):
#             cities[user.city] = 1
#         else:
#             cities[user.city] += 1

#     for key in cities:
#         print key, cities[key]
        


