#!/usr/bin/python
import urllib,re,os,Image,time,sys,shutil,ImageDraw,ImageFont
# Show the Bern weather forecast in the next three days in a small window
# Requires: ImageMagick, html2ps, xloadimage

url='http://www.espace.ch'
tabBlock='espace // wetter'
#tabBlock='zueritipp.ch'
tab='</table>'
hfn='/tmp/bund.html'
wDir='/var/www/img/wetter/'
pfn='%s%s.png' % (wDir,time.strftime('%y-%m-%d',time.localtime()))
tfn='/tmp/bund.png'
oFile='/var/www/img/wetter.png'
head='<html><body>\n'
bord=5
mainFont='/usr/share/fonts/corefonts/arial.ttf'
arial=ImageFont.truetype(mainFont,10)
breite=14
lbord=10
rbord=7
bgcol=(220,230,250)

def merge(wDir,oFile):
 bilder=os.listdir(wDir)
 nb=len(bilder)
 print 'Bilder: %d' % nb
 bilder.sort()
 first=Image.open(wDir+bilder[0])
 startTime=os.stat(wDir+bilder[0])[8]
 fx,fy=first.size
 fx=fx/3-rbord
 im=Image.new('RGB',(fx*breite+lbord+rbord,fy*(nb/breite+1)),bgcol)
 draw = ImageDraw.Draw(im)
 lmon=''
 for n,i in enumerate(bilder):
  pos=(n%breite*fx+lbord,n/breite*fy)
  nim=Image.open(wDir+i)
  cnim=nim.crop((0,0,fx,fy))
  for cj in range(cnim.size[1]):
   for ci in range(cnim.size[0]):
    if cnim.getpixel((ci,cj))==(255,255,255): cnim.putpixel((ci,cj),bgcol)	
  im.paste(cnim,pos)
  nun=time.gmtime(startTime+n*3600*24)
  datum=time.strftime('%b.',nun)
  if not n%breite and not lmon==datum: 
   draw.text((pos[0]-lbord+1,pos[1]-1),datum,fill='red',font=arial)
   lmon=datum
 im.save(oFile)
 print '%s written' % oFile

def crop(fn):
 im = Image.open(fn)
 (x,y)=im.size
 img=im.convert('RGB')
 kord=[]
 print 'Scanning %d pixels for black pixels...' % (x*y)
 for j in range(y):
  for i in range(x):
   p=img.getpixel((i,j))
   if p==(0,0,0): kord.append((i,j))
 xk,yk=map(lambda x:x[0],kord),map(lambda x:x[1],kord)
 x1,x2,y1,y2=min(xk),max(xk),min(yk),max(yk)
 print 'Saving crop %d/%d, %d/%d to %s...' % (x1,y1,x2,y2,fn)
 imgc=img.crop((x1-bord,y1-bord,x2+bord,y2+bord))
 imgc.save(fn)

def fSize(f): return os.stat(f)[6]
print 'Fetching %s...' % url
bund=urllib.urlopen(url).read()
block=filter(lambda x : x.find(tabBlock)>-1,bund.lower().split(tab))[0]
block=block.split('zueritipp.ch</a>')[1] # fixed 2008-02-23
nodiv=re.compile('<div.+?>')
nocom=re.compile('<!--.+?-->')
block=nodiv.sub('',block).replace('</div>','')
block=nocom.sub('',block).replace(tabBlock,'').replace('100%','150')
cont=block.replace('src="','src="'+url)
cont='\n'.join(filter(lambda x : len(x)>5,cont.split('\n')))
cont=cont.upper().replace('NBSP','nbsp').replace('DEG','deg')
open(hfn,'w').write(head+cont+tab+'</body></html>')
os.system('convert %s %s'%(hfn,tfn))
crop(tfn)
eMsg='%s of the same size and name exists. No need to save.' 
if os.path.isfile(pfn):
 if fSize(pfn)==fSize(tfn):
  print eMsg % pfn
  sys.exit()
 pfn='%s%s.png' % (wDir,time.strftime('%y-%m-%d',time.localtime(time.time()+3600*24)))
 if os.path.isfile(pfn):
  if fSize(pfn)==fSize(tfn):
   print eMsg % pfn
   sys.exit()
shutil.move(tfn,pfn)
merge(wDir,oFile)