diff --git a/modules/coffee.go b/modules/coffee.go index ade3de3..9b22122 100644 --- a/modules/coffee.go +++ b/modules/coffee.go @@ -7,12 +7,26 @@ package modules import ( + "fmt" + "log" "strings" + "sync" "time" "code.dnix.de/an/xlog" "github.com/sorcix/irc" + "github.com/sorcix/irc/ctcp" +) + +type Receivers struct { + names map[string]bool + running bool + mux sync.Mutex +} + +var ( + r Receivers ) func init() { @@ -29,30 +43,91 @@ func coffeeHandleMessage(m *irc.Message) { case "!kaffee": switch len(tok) { case 1: - go coffeeMake(nil) + go r.addReceivers(nil) default: - go coffeeMake(tok[1:]) + go r.addReceivers(tok[1:]) } default: } } -func coffeeMake(rec []string) { - SayCh <- "*\nsetzt Kaffee auf." - time.Sleep(30 * time.Second) - SayCh <- "*\nstellt eine frische Kanne Kaffee in den Raum." - if rec != nil { +func (r *Receivers) addReceivers(newNames []string) { + r.mux.Lock() + if r.running { + SayCh <- "*\nEs wird gerade Kaffee zubereitet." + if newNames != nil { + r.addNames(newNames) + } + } else { + if newNames != nil { + r.addNames(newNames) + } + go makeCoffee() + } + r.mux.Unlock() +} + +func (r *Receivers) makeCoffee() { + printAction("setzt Kaffee auf.") + time.Sleep(time.Second * 30) + printAction("stellt eine frische Kanne Kaffee in den Raum.") + r.mux.Lock() + if len(r.names) != 0 { var users string - for i, v := range rec { - users += v - if i < len(rec)-2 { + for i, _ := range r.names { + users += i + /*if i < len(rec)-2 { users += ", " } else if i == len(rec)-2 { users += " und " - } + }*/ } SayCh <- "*\ngibt " + users + " einen frischen, richtig schwarzen, richtig leckeren Kaffee." } time.Sleep(10 * time.Second) SayCh <- "*\nProst! (c)" + + r.names = make(map[string]bool) + r.running = false + + r.mux.Unlock() } + +func (r *Receivers) addNames(newNames []string) { + for _, v := range newNames { + r.names[v] = true + } +} + +func printAction(s string) { + msg := ctcp.Encode(ctcp.ACTION, fmt.Sprintf(s)) + SayCh <- fmt.Sprintf("%s\n%s", "*", msg) +} + +//func (r *Receivers) coffeeMake(rec []string) { +// if *running { +// // TODO: add new recipients to map +// // no if rec == nil add the sender, else add the sender and rec +// SayCh <- "*\nEs wird gerade Kaffee zubereitet." +// } else { +// printAction("setzt Kaffee auf.") +// time.Sleep(30 * time.Second) +// printAction("stellt eine frische Kanne Kaffee in den Raum.") + +// if rec != nil { +// var users string +// for i, v := range rec { +// users += v +// if i < len(rec)-2 { +// users += ", " +// } else if i == len(rec)-2 { +// users += " und " +// } +// } +// SayCh <- "*\ngibt " + users + " einen frischen, richtig schwarzen, richtig leckeren Kaffee." +// } + +// time.Sleep(10 * time.Second) +// SayCh <- "*\nProst! (c)" +// } +//}