
from urllib.request import urlopen

import lxml.html
from lxml.cssselect import CSSSelector

from i3pystatus import IntervalModule

class TrackerAPI:
    def __init__(self, idcode):
        pass

    def status(self):
        return {}

class DHL(TrackerAPI):
    URL="http://nolp.dhl.de/nextt-online-public/set_identcodes.do?lang=en&idc={idcode}"
    def __init__(self, idcode):
        self.idcode = idcode
        self.url = self.URL.format(idcode=self.idcode)

        self.progress_selector = CSSSelector(".greyprogressbar > span, .greenprogressbar > span")
        self.last_status_selector = CSSSelector(".events .eventList tr")
        self.intrarow_status_selector = CSSSelector("td.status div")

    def status(self):
        ret = {}
        with urlopen(self.url) as page:
            page = lxml.html.fromstring(page.read())
            ret["progress"] = self.progress_selector(page)[0].text.strip()
            last_row = self.last_status_selector(page)[-1]
            ret["status"] = self.intrarow_status_selector(last_row)[0].text.strip()
        return ret

class ParcelTracker(IntervalModule):
    interval = 20

    settings = (
        ("instance", "Tracker instance"),
        "format",
        "name",
    )
    required = ("instance",)

    format = "{name}:{progress}"

    def run(self):
        fdict = {
            "name": self.name,
        }
        fdict.update(self.instance.status())

        self.output = {
            "full_text": self.format.format(**fdict).strip(),
            "instance": self.name,
        }

@@ -459,16 +459,144 @@
 dcode)%0A%0A
+        error_selector = CSSSelector(%22#set_identcodes .error%22)%0A        self.error = lambda page: len(error_selector(page)) %3E= 1%0A
         
@@ -960,16 +960,127 @@
 read())%0A
+            if self.error(page):%0A                ret%5B%22progress%22%5D = ret%5B%22status%22%5D = %22n/a%22%0A            else:%0A    
         
@@ -1138,32 +1138,36 @@
 0%5D.text.strip()%0A
+    
             last
@@ -1209,16 +1209,20 @@
 ge)%5B-1%5D%0A
+    
         

Add display for parcels not yet showing up in tracking.