package require msgcat 
package require http

namespace eval ljpost {}

proc ljpost::open_post_window { } {
variable options

	set mw ._livejournal

    if { [winfo exists $mw] } { destroy $mw }
	
	wm group [toplevel $mw] .
	wm title $mw "LiveJournal post"
    wm iconname $mw "LiveJournal post"
	
	wm resizable $mw 0 0
	
	wm state $mw withdraw
	
	set bb ${mw}.buttonbar
	frame $bb -bd 1 -relief raised
	
	set login ${mw}.login
	frame $login -bd 1 -relief raised
	
	set text ${mw}.text
	frame $text -bd 1 -relief raised
	
    pack $bb $login $text -fill x -expand 1

	menubutton $bb.mb -text [::msgcat::mc File] -menu  $bb.mb.f 
	menubutton  $bb.ed -text [::msgcat::mc Edit] -menu $bb.ed.t 
	menubutton  $bb.ins -text [::msgcat::mc Insert] -menu  $bb.ins.t 
	
	menu $bb.mb.f -tearoff 1
	$bb.mb.f add command -label [::msgcat::mc "Open"] \
		-command [list [namespace current]::file_open $mw $text.txt]
	$bb.mb.f add command -label  [::msgcat::mc "Save"] \
		-command  [list [namespace current]::file_save $mw $text.txt]
	$bb.mb.f  add command -label [::msgcat::mc "Save As ..."] \
		-command  [list [namespace current]::file_save_as $mw $text.txt] 
	$bb.mb.f add command -label [::msgcat::mc "Clear"] \
		-command  [list [namespace current]::clear $mw $text.txt]
	$bb.mb.f  add separator
	$bb.mb.f add command -label [::msgcat::mc "Post"] \
		-command  [list [namespace current]::post $mw $text.txt] 
	$bb.mb.f add separator
	$bb.mb.f  add command -label [::msgcat::mc "Return to Tkabber"] \
		-command  [list [namespace current]::quit $mw $text.txt]
		
	menu $bb.ed.t -tearoff 1
	$bb.ed.t add command -label [::msgcat::mc "Cut"] \
		-command  [list [namespace current]::cut $text.txt]
	$bb.ed.t add command -label [::msgcat::mc "Copy"] \
		-command  [list [namespace current]::copy $text.txt]
	$bb.ed.t add command -label [::msgcat::mc "Paste"] \
		-command  [list [namespace current]::paste $text.txt]
	$bb.ed.t add command -label [::msgcat::mc "Undo"] \
		-command  [list [namespace current]::undo $text.txt]
	$bb.ed.t add command -label [::msgcat::mc "Redo"] \
		-command  [list [namespace current]::redo $text.txt]
	$bb.ed.t add command -label [::msgcat::mc "Select all"] \
		-command  [list [namespace current]::select_all $text.txt]
	$bb.ed.t add separator
	$bb.ed.t add command -label [::msgcat::mc "Word Count"] \
		-command  [list [namespace current]::wordcount $mw $text.txt] 
	$bb.ed.t add command -label [::msgcat::mc "Time Stamp"] \
		-command  [list [namespace current]::time_stamp $text.txt]

	menu $bb.ins.t -tearoff 1
	$bb.ins.t add command -label [::msgcat::mc "Bold"] \
		-command  [list [namespace current]::insert_bold $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Italic"] \
		-command  [list [namespace current]::insert_italic $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Underline"] \
		-command  [list [namespace current]::insert_underline $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Strike"] \
		-command  [list [namespace current]::insert_strike $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Bullets"] \
		-command  [list [namespace current]::insert_bullets $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Numbering"] \
		-command  [list [namespace current]::insert_numbering $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Date"] \
		-command  [list [namespace current]::insert_date $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Text align - center"] \
		-command  [list [namespace current]::align_center $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Text align - full"] \
		-command  [list [namespace current]::align_full $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Text align - left"] \
		-command  [list [namespace current]::align_left $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Text align - right"] \
		-command  [list [namespace current]::align_right $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "LiveJournal Community"] \
		-command  [list [namespace current]::insert_community $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "LiveJournal User"] \
		-command  [list [namespace current]::insert_user $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Image link"] \
		-command  [list [namespace current]::insert_image $text.txt]
	$bb.ins.t add command -label [::msgcat::mc "Color tag"] \
		-command  [list [namespace current]::insert_color $text.txt]

	pack $bb.mb $bb.ed $bb.ins -side left

	grid [label $login.ljname -text [::msgcat::mc "LJ Username:"]] \
		[entry $login.uname -textvariable [namespace current]::options(ljname)] \
		[label $login.pwd -text [::msgcat::mc "LJ Password:"]] \
		[entry $login.pswd -show * -textvariable [namespace current]::options(ljpswrd)] \
		[label $login.sujet -text [::msgcat::mc "Subject:"]] \
		[entry $login.assunto -textvariable [namespace current]::options(subject)]

	grid [label $login.md -text [::msgcat::mc "Current mood:"]] \
		[entry $login.mude -textvariable [namespace current]::options(mood)] \
		[label $login.tunages -text [::msgcat::mc "Current music:"]] \
		[entry $login.tunez -textvariable [namespace current]::options(tunes)] \
		[label $login.oj -text [::msgcat::mc "Post to:"]] \
		[entry $login.uj -textvariable [namespace current]::options(usej)] 

	grid [label $login.tagz -text [::msgcat::mc "Tags:"]] \
		[entry $login.tagit -textvariable [namespace current]::options(tags)] 	
		
	text $text.txt -yscrollcommand [list $text.ys set] \
		-maxundo 0 -undo true -wrap word
	scrollbar $text.ys -command [list $text.txt yview]

	pack $text.txt -side left -fill both -expand true

	pack $text.ys -side left -fill y
	
	wm state $mw normal
	
	[namespace current]::reset_file $mw
	[namespace current]::load_state $mw $text.txt
}

proc ljpost::load_state { w text } {
variable options
	$text insert end $options(text)
}

proc ljpost::file_open { w text } {
variable options
	
	wm state $w withdraw
	set options(filename) \
		[tk_getOpenFile -filetypes $options(filetypes)]
	
	if { $options(filename) eq {} } { 
		wm state $w normal
		focus $w
		return 
	}
	
	wm title $w [::msgcat::mc "File: %s" $options(filename)]
	set data [open $options(filename) RDWR]
	$text delete 1.0 end
	
	while {![eof $data]} {
		$text insert end [read $data 1000]
	}
	
	close $data
	$text mark set insert 1.0
	
	wm state $w normal
	focus $w
}

proc ljpost::file_save { w text} {
variable options
	
	if { $options(filename) ne {} } {
	
	set data [$text get 1.0 {end -1c}]
	set fileid [open $options(filename) WRONLY]
	
	puts $fileid $data
	
	close $fileid
	
	tk_messageBox -message [::msgcat::mc "Saved to %s" $options(filename)]
	focus $w
	
	} else {
		[namespace current]::file_save_as $w $text
	}
}

proc ljpost::file_save_as { w  text } {
variable options

	wm state $w withdraw
	set options(filename) \
		[tk_getSaveFile -filetypes $options(filetypes) \
			-initialfile $options(filename)]
	
	if { $options(filename) eq {} } { 
		wm state $w normal
		focus $w
		return 
	}
	
	wm title $w [::msgcat::mc "File: %s" $options(filename)]
	
   set data [$text get 1.0 {end -1c}]
   
   set fileid [open $options(filename) WRONLY]
   
	puts $fileid $data
	
   close $fileid
	
	tk_messageBox -message [::msgcat::mc "Saved to %s" $options(filename)]
	
	wm state $w normal
	focus $w
}

proc ljpost::clear { w text } {
variable options
	
	wm state $w withdraw
	
	if { [$text edit modified] } {
		set answer [tk_messageBox -message [::msgcat::mc "Would you like to save your work?"] \
			-title [::msgcat::mc "Clear ..."] -type yesnocancel \
			-icon question]
		
		if { $answer eq "yes" } { 
			[namespace current]::file_save $w $text 
			[namespace current]::clear_text $w $text 
		} else {
			[namespace current]::clear_text $w $text
		}
	}
	
	wm state $w normal
	focus $w
}

proc ljpost::reset_file { w } {
variable options
	set options(filename) {}
	wm title $w "LiveJournal post"
}

proc ljpost::clear_text { w text } {
variable options

	$text delete 1.0 end
	$text edit reset
	$text edit modified 0
	[namespace current]::reset_file $w
}

proc ljpost::quit { w text } { 
variable options

	if { $options(save_state) } {
	set options(text) [$text get 1.0 {end -1c}]
	}
	
	destroy $w 
}

proc ljpost::create_time { } {
variable options 

	set options(year) [clock format [clock second] -format %Y]
	set options(mon) [clock format [clock seconds] -format %m]
	set options(day) [clock format [clock seconds] -format %d]
	set options(hour) [clock format [clock seconds] -format %H]
	set options(min) [clock format [clock seconds] -format %M]
}

proc ljpost::post { w text } {
variable options
   
   [namespace current]::create_time
   
	set data [$text get 1.0 {end -1c}]
	append data \n[::msgcat::mc "Posted from lj_post - Tkabber plugin"]
	
	set url "http://www.livejournal.com/interface/flat:80"
	
	set login [::http::formatQuery mode login user $options(ljname) password $options(ljpswrd) ]
	set log [http::geturl $url -query $login]
		
	set post [::http::formatQuery mode postevent \
		auth_method clear \
		user $options(ljname) \
		password $options(ljpswrd) \
		subject $options(subject) \
		year $options(year) \
		mon $options(mon) \
		day $options(day) \
		hour $options(hour) \
		min $options(min) \
		prop_current_music $options(tunes) \
		prop_current_mood $options(mood) \
		prop_taglist $options(tags) \
		usejournal $options(usej) \
		event $data ]
	
	set plength [string length $post]
	set dopost [http::geturl $url -query $post]
	set ljmta [http::meta $dopost]
	set ljl [http::size $dopost]
	set ljstat [http::status $dopost]

	tk_messageBox \
		-message [::msgcat::mc "LiveJournal says: %s Post length: %s" $ljstat $ljl] \
		-title [::msgcat::mc "Post"]
}

proc ljpost::undo text {
	catch {$text edit undo}
}

proc ljpost::redo text {
	catch {$text edit redo}
}

proc ljpost::select_all text {
	$text tag add sel 1.0 end
}

proc ljpost::paste text {
	global tcl_platform
	if {![catch {::tk::GetSelection $text CLIPBOARD} sel]} {
		set oldSeparator [$text cget -autoseparators]
		if {$oldSeparator} {
			$text configure -autoseparators 0
			$text edit separator
		}
		if {[tk windowingsystem] ne "x11"} {
			catch { $text delete sel.first sel.last }
		}
		$text insert insert $sel
		if {$oldSeparator} {
			$text edit separator
			$text configure -autoseparators 1
		}
	}
}


proc ljpost::copy text {
	if {![catch {set data [$text get sel.first sel.last]}]} {
		clipboard clear -displayof $text
		clipboard append -displayof $text $data
	}
}

proc ljpost::cut text {
	if {![catch {set data [$text get sel.first sel.last]}]} {
		clipboard clear -displayof $text
		clipboard append -displayof $text $data
		$text delete sel.first sel.last
	}
}

proc ljpost::wordcount { w text } {
	set wordsnow [$text get 1.0 {end -1c}]
	set wordlist [split $wordsnow]
	
	set countnow 0
	foreach item $wordlist {
		if { $item ne {} } {
			incr countnow
		}
	}
	
	tk_messageBox \
		-message [::msgcat::mc "Current count: %s words" $countnow] \
		-title [::msgcat::mc "Word Count"]
	
	focus $w
}

proc ljpost::time_stamp text {
	set date [clock format [clock seconds] \
		-format "%R %p %D"]
		
	$text insert insert $date
}

proc ljpost::insert_tags { text tag_one tag_two} {
	if {![catch {$text get sel.first sel.last} sel]} {
		$text delete sel.first sel.last
		$text insert insert " ${tag_one}${sel}${tag_two} "
	} else {
		$text insert insert " ${tag_one}${tag_two}"
		$text mark set insert "insert -[string length $tag_two] chars"
	}
}

proc ljpost::insert_bold text {
	[namespace current]::insert_tags $text <b> </b>
}

proc ljpost::insert_italic text {
	[namespace current]::insert_tags $text <i> </i>
}

proc ljpost::insert_underline text {
	[namespace current]::insert_tags $text <u> </u>
}

proc ljpost::insert_strike text {
	[namespace current]::insert_tags $text <strike> </strike>
}

proc ljpost::insert_bullets text {
	[namespace current]::insert_tags $text <ul>\n<li> </li>\n</ul>
}

proc ljpost::insert_numbering text {
	[namespace current]::insert_tags $text <ol>\n<li> </li>\n</ol>
}

proc ljpost::insert_date text {
	set date [clock format [clock seconds] -format "%R %p %D"]
	$text insert insert "$date "
}

proc ljpost::align_center text {
	[namespace current]::insert_tags $text "<div style='text-align: center;'>" "</div>"
}

proc ljpost::align_full text {
	[namespace current]::insert_tags $text {<div align=justify>} {</div>}
}

proc ljpost::align_left text {
	[namespace current]::insert_tags $text {<div style='text-align: left;'>} {</div>}
}

proc ljpost::align_right text {
	[namespace current]::insert_tags $text {<div style='text-align: right;'>} {</div>}
}

proc ljpost::insert_community text {
	[namespace current]::insert_tags $text {<lj comm='} {'>}
}

proc ljpost::insert_user text {
	[namespace current]::insert_tags $text {<lj user='} {'>}
}

proc ljpost::insert_image text {
	[namespace current]::insert_tags $text {<img src='} {'>}
}

proc ljpost::insert_color text {
	set color [tk_chooseColor]
	[namespace current]::insert_tags $text "<font color='$color'>" {</font>}
	focus $text 
}

proc ljpost::load_button { } {
variable options
	
	set image [file join $options(script_dir) images livejournal_button.gif]
	set icon [image create photo -file $image]
	
	::ifacetk::add_toolbar_button $icon \
		[namespace current]::open_post_window \
		[::msgcat::mc "LiveJournal"]
}

namespace eval ljpost {
	custom::defgroup Plugins [::msgcat::mc "Plugins options."] -group Tkabber
	
	custom::defgroup {LiveJournal Post} \
		[::msgcat::mc "The plugin allows you to quickly\
		add new entries to the specified journal"] \
		-group Plugins
		
	custom::defvar options(save_state) yes \
		[::msgcat::mc "Save the state at the close plugin window"] \
		-group {LiveJournal Post} -type boolean
	
	custom::defgroup Account \
		[::msgcat::mc "Account settings"] \
		-group {LiveJournal Post}	
		
	custom::defvar options(ljname) "" \
		[::msgcat::mc "Username to LiveJournal.com"] \
		-group Account -type string
		
	custom::defvar options(ljpswrd) "" \
		[::msgcat::mc "Password to LiveJournal.com"] \
		-group Account -type string
		
	custom::defvar options(subject) [::msgcat::mc "subject"] \
		[::msgcat::mc "Default subject"] \
		-group Account -type string
		
	custom::defvar options(mood) [::msgcat::mc "mood"] \
		[::msgcat::mc "Default mood"] \
		-group Account -type string
		
	custom::defvar options(tunes) [::msgcat::mc "music"] \
		[::msgcat::mc "Music"] \
		-group Account -type string
		
	custom::defvar options(usej) "" \
		[::msgcat::mc "Default Journal"] \
		-group Account -type string
	
	custom::defvar options(tags) [::msgcat::mc "enter, tags, here"] \
		[::msgcat::mc "Default tags"] \
		-group Account -type string
		
	set options(script_dir) [file dirname [info script]]
	set options(filetypes) [list {"All Files" * } {"Text Files" { .txt .TXT}}]
	set options(filename) {}
	set options(text) {}
	
	::msgcat::mcload [file join $options(script_dir) msgs]
	
	hook::add finload_hook [namespace current]::load_button
}