#!/usr/local/bin/tclkit

package require Tk
package require BWidget
package require tdom
package require http

option add *Frame.background white
option add *Label.background white
option add *font {Helvetica 10}

set feeds {Dilbert Peanuts {User Friendly}}
array set feedURLs {
    test file:/home/anselm/test.rdf
    Dilbert http://dwlt.net/tapestry/dilbert.rdf
    Peanuts http://dwlt.net/tapestry/peanuts.rdf
    {User Friendly} http://dwlt.net/tapestry/uf.rdf
}

proc getByHTTP {url} {
    set h [http::geturl $url]
    set result [http::data $h]
    http::cleanup $h
    return $result
}

set statusMsg {}
proc startStatus {} {
    wm withdraw .
    catch { unset .status }
    toplevel .status -background white
    wm overrideredirect .status
    wm geometry .status +10+10
    label .status.l1 -text "tkTapestry" -font {Helvetica 16 bold}
    label .status.l2 -width 60 -textvariable statusMsg
    pack .status.l1 .status.l2 -side top
    update
}

proc status {msg} {
    global statusMsg
    set statusMsg $msg
    update
}

proc stopStatus {} {
    destroy .status
    wm deiconify .
    update
}

proc getImgURLs {} {
    global feeds feedURLs
    global imgURLs

    status "Getting RDF feeds"
    foreach feed $feeds {
	status "Getting RDF feed: $feed"
	set doc [dom parse [getByHTTP $feedURLs($feed)]]
	set itemList [$doc getElementsByTagName item]
	set imgURLs($feed) {}
	foreach i $itemList {
	    foreach c [$i childNodes] {
		if {[$c nodeName] eq "title"} {
		    set title [$c text]
		} elseif {[$c nodeName] eq "description"} {
		    regexp {src="(.*?)"} [$c text] -> imgURL
		}
	    }
	    lappend imgURLs($feed) [list $title $imgURL]
	}
    }
    status "Done"
}

set count 0
proc makeImg {w feed index} {
    global count imgURLs

    foreach {title url} [lindex $imgURLs($feed) 0] break

    status "Retrieving image: $title"
    set img [image create photo -data [getByHTTP $url]]

    set f [frame $w.f$count]
    incr count

    label $f.title -text $title -anchor w
    frame $f.buttons
    button $f.buttons.save -text Save -command [list saveImg $img]
    button $f.buttons.more -text More -command [list moreImgs $feed]
    pack $f.buttons.save $f.buttons.more -side right

    label $f.img -image $img

    grid $f.title $f.buttons -sticky we
    grid $f.img -
    grid columnconfigure $f 0 -weight 1
    return [list $f [expr {[image width $img]+4}]]
}

wm title . Comics

ScrolledWindow .f
ScrollableFrame .f.f -height 600
pack .f -fill both -expand yes
.f setwidget .f.f

startStatus
getImgURLs
set maxWidth 0
foreach f $feeds {
    foreach {img width} [makeImg [.f.f getframe] $f 0] break
    pack $img -side top -fill x -expand yes
    if {$width > $maxWidth} {
	.f.f configure -width $width
	set maxWidth $width
    }
}
status "Done"
stopStatus

