# coding: utf-8
from selenium import webdriver
import lxml.html
import tsc.db
from pprint import pprint

class TeacherScheduleFetcher:

    def __init__(self):
        self.browser = webdriver.PhantomJS()
        #self.browser = webdriver.Firefox()
        self.conn = tsc.db.connect()

    def fetch(self, teacher_id):
        url_base = "http://eikaiwa.dmm.com/teacher/index/{0}/"
        b = self.browser
        b.get(url_base.format(teacher_id))

        root = lxml.html.fromstring(b.page_source)
        title = root.xpath("//title")[0].text
        name = title.split("-")[0].strip()
        with self.conn.cursor() as cursor:
            cursor.execute(
                "INSERT INTO teacher VALUES (%s, %s) ON DUPLICATE KEY UPDATE name=%s",
                (teacher_id, name, name,)
            )

        times = root.xpath("//ul[@class='oneday']//li")
        for time in times:
            print("time = ", time.text.strip(), time.attrib["class"])
        #pprint(date)


    def close(self):
        self.conn.close()
        self.browser.quit()

@@ -9,16 +9,43 @@
 : utf-8%0A
+import datetime%0Aimport re%0A%0A
 from sel
@@ -102,34 +102,9 @@
 .db%0A
-from pprint import pprint
 %0A
+
 %0Acla
@@ -810,20 +810,62 @@
         
-time
+date = datetime.date.today()%0A        time_item
 s = root
@@ -920,16 +920,21 @@
 time
+_item
  in time
 s:%0A 
@@ -933,11 +933,119 @@
 time
+_item
 s:%0A
+            time_class = time_item.attrib%5B%22class%22%5D%0A            text = time_item.text_content().strip()%0A
     
@@ -1063,81 +1063,791 @@
 nt(%22
+%7B
 time
- = %22, time.text.strip(), time.attrib%5B%22class%22%5D)%0A        #pprint(date)%0A
+_class%7D:%7Btext%7D%22.format(**locals()))%0A            # blank, reservable, reserved%0A            #date_str = %22%22%0A            if time_class == %22date%22:%0A                match = re.match(r%22(%5B%5Cd%5D+)%E6%9C%88(%5B%5Cd%5D+)%E6%97%A5(.+)%22, text)%0A                if match:%0A                    #print(match.group(1), match.group(2))%0A                    date = date.replace(date.year, int(match.group(1)), int(match.group(2)))%0A                    print(date)%0A                #print(date_str)%0A            elif time_class.startswith(%22t-%22):%0A                tmp = time_class.split(%22-%22)%0A                tmp%5B1%5D, tmp%5B2%5D%0A            else:%0A                pass%0A%0A        %22%22%22%0A        t-22-30:%E4%BA%88%E7%B4%84%E6%B8%88%0A        t-23-00:%0A        t-23-30:%0A        t-24-00:%0A        t-24-30:%0A        t-25-00:%0A        t-25-30:%0A        date:10%E6%9C%8828%E6%97%A5(%E6%B0%B4)%0A        %22%22%22
 %0A%0A  

parse date