#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @author starenka
# @contact admin@starenka.net
# @version 0.1.1
from smtplib import SMTP
from datetime import date
import urllib2,re,string

SERVER = 'smtp.server.net'
USER = 'smtp_login'
PASS = 'smtp_pass'
FROM = "s@t.a"
TO = "12345689@sms.cz.o2.com"
MAX_CHARS = 51
debuglevel = 0

date_m = re.compile(r'.*?<td class="nowrap"><a.*?>(.*?)</a>.*?',re.IGNORECASE)
all_m = re.compile(r'.*?<td>(.*?)</td>.*?',re.IGNORECASE)

def html2text(str):
    str = str.replace('&nbsp;',' ')
    str = str.replace('<br />',' ')
    s = re.compile('<\/?strong>')
    str = s.sub('',str)
    return str

request = urllib2.Request('http://www.dpp.cz/vsechna-omezeni-dopravy/')
try: response = urllib2.urlopen(request)
except urllib2.HTTPError, e: pass
except urllib2.URLError, e: pass
else: data = response.read()

dates = []
lines = []
types = []
if data:
    for match in re.finditer(date_m,data):
        dates.append(match.group(1).replace(' ',''))
    c = 0
    for match in re.finditer(all_m,data):
        if c == 0: lines.append(html2text(match.group(1).replace(', ',',')))
        if c == 1: types.append(html2text(match.group(1).replace('ostatní','')))
        c+=1
        if c == 2: c = 0

mess = ''
d = date.today()
today = '%s.%s' % (str(int(d.strftime('%d'))),str(int(d.strftime('%m')))) #ehehe strip leading 0
for i in range(0,len(dates)):
    if dates[i].find(today) != -1:
        mess += '%s|%s|%s$' % (dates[i],lines[i],types[i])

msg_parts = []
start = 0
for i in range(0,len(mess)/MAX_CHARS+1):
    msg_parts.append(mess[start:start+MAX_CHARS])
    start += MAX_CHARS
msg_parts.reverse()

smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect(SERVER, 26)
smtp.login(USER,PASS)

for m in msg_parts:
    msg = ("From: %s\r\nTo: %s\r\n\r\n" % (FROM,TO))
    msg = msg + m
    smtp.sendmail(FROM,TO,msg)
smtp.quit()