package main

import (
	"context"
	"crypto/tls"
	"flag"
	"log"
	"math/rand"
	"net"
	"strings"
	"time"

	"github.com/fluffle/goirc/client"
	"github.com/tcolgate/hugot"
	"github.com/tcolgate/hugot/adapters/irc"

	"ur.gs/lysenko/handlers/deadline"
	"ur.gs/lysenko/handlers/quotedb"
)

var (
	channels = flag.String("channels", "##testing,##test", "Channels to join (separated by comma)")
	host     = flag.String("host", "chat.freenode.net", "Server host[:port]")
	ident    = flag.String("ident", "lysenko", "Lysenko Bot")
	nick     = flag.String("nick", "lysenko", "Lysenko Bot")
	nickserv = flag.String("nickserv", "", "NickServ password")
	quotes   = flag.String("quotedb", ":memory:", "sqlite3 quote database")
	ssl      = flag.Bool("ssl", true, "Enable SSL")
)

func init() {
	// TODO: better rand.Seed
	rand.Seed(time.Now().Unix())
}

func main() {
	flag.Parse()

	channelList := strings.Split(*channels, ",")
	config := client.NewConfig(*nick, "lysenko", "Comrade Trofim Lysenko")
	config.Server = *host
	config.Pass = *nickserv
	config.SSL = *ssl

	if config.SSL {
		hostname, _, err := net.SplitHostPort(config.Server)
		if err != nil {
			log.Fatal(err)
		}
		config.SSLConfig = &tls.Config{
			ServerName: hostname,
		}
	}

	adapter := irc.New(config, channelList...)

	db, err := quotedb.New(*quotes)
	if err != nil {
		log.Fatal(err)
	}
	defer db.DB.Close()

	mux := hugot.DefaultMux
	mux.HandleCommand(&quotedb.AddQuoteHandler{QuoteDB: db})
	mux.HandleCommand(deadline.NewCommand(&quotedb.LastQuoteHandler{QuoteDB: db}))
	mux.HandleCommand(deadline.NewCommand(&quotedb.FindQuoteHandler{QuoteDB: db}))
	mux.HandleCommand(deadline.NewCommand(&quotedb.RandQuoteHandler{QuoteDB: db}))
	mux.HandleCommand(deadline.NewCommand(&quotedb.QuoteHandler{QuoteDB: db}))

	hugot.ListenAndServe(context.Background(), mux, adapter)
}
