#!/usr/bin/python

import getpass
import time
import sys

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


class Wishlist(object):

    def __init__(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(10)

    def login(self, email, passwd):
        self.driver.get('http://passport.dx.com//accounts/default.dx')
        assert 'DX Account Manager' in self.driver.title

        email_field = self.driver.find_element_by_id('ctl00_content_txtLoginEmail')
        email_field.send_keys(email)
        
        pw_field = self.driver.find_element_by_id('ctl00_content_txtPassword')
        pw_field.send_keys(passwd + Keys.RETURN)

        time.sleep(2)

    def goto(self, link):
        self.driver.get(link)
        time.sleep(5)        

    def getWishlistPages(self):
        self.goto('http://my.dx.com/Wishlist/Index')

        page_list = self.driver.find_element_by_class_name('page')
        a_tags = page_list.find_elements_by_tag_name('a')
        links = [a.get_attribute('href') for a in a_tags][2:-1]
        sys.stderr.write(','.join(links) + '\n')

        return links

    def getProductItems(self):
        prodcuts_list = self.driver.find_element_by_class_name('wishlist_pros')
        a_tags = prodcuts_list.find_elements_by_xpath('.//p[contains(@class, "title")]/a')
        
        result = []
        for a in a_tags:
            link = a.get_attribute('href')
            sku = link.split('/')[-1]
            title = a.text
            result.append((sku, title))

        sys.stderr.write('Found %d products\n' % len(result))
        return result


email = raw_input('DX e-mail login: ')
pw = getpass.getpass('DX password: ')

wl = Wishlist()
wl.login(email, pw)
pages = wl.getWishlistPages()
products = wl.getProductItems()
for p in pages:
    wl.goto(p)
    products += wl.getProductItems()

for p in products:
    print '%s,"%s"' % p
