# $Id$

namespace eval plugins {
}

proc plugins::require_hook {hook} {
    variable $hook
    if {![info exists $hook]} {
        set $hook {}
    }
}

proc plugins::add_hook {hook func priority} {
    variable $hook

    lappend $hook [list $func $priority]
    set $hook [lsort -integer -index 1 [set $hook]]
}

proc plugins::require_flag {hook flag} {
    variable F

    if {![info exists F(flags,$hook)]} {
	set F(flags,$hook) {}
    }

    if {![lcontain $F(flags,$hook) $flag]} {
	if {!([llength $F(flags,$hook)] > 30)} {
	    lappend F(flags,$hook) $flag
	} else {
	    puts "Too many flags"
	    exit
	}
    }
}

proc plugins::set_flag {hook flag} {
    variable F
    
    set i [lsearch -exact $F(flags,$hook) $flag]
    set F(state,$hook) [expr $F(state,$hook) | (1 << $i)]
}

proc plugins::unset_flag {hook flag} {
    variable F
    
    set i [lsearch -exact $F(flags,$hook) $flag]
    set F(state,$hook) [expr $F(state,$hook) & ~(1 << $i)]
}

proc plugins::is_flag {hook flag} {
    variable F
    
    set i [lsearch -exact $F(flags,$hook) $flag]
    return [expr $F(state,$hook) & (1 << $i)]
}

proc plugins::load {dir} {
    #variable $plugins

    foreach file [glob -nocomplain $dir/*.tcl] {
	puts "Loading plugin from $file"
	source $file
    }
}


proc plugins::run_hook {hook args} {
    variable F
    variable $hook
    
    set F(state,$hook) [expr ~0]
    
    foreach func [set $hook] {
	set func [lindex $func 0]
	set state [eval $func $args]
	if {[cequal $state stop]} {
	    break
	}
    }
}

#plugins::load chat-plugins
#plugins::load chat-plugins
#puts $plugins::chat_send_message

#plugins::run_hook chat_send_message args





#exit

