package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/facebookarchive/flagenv"
	_ "github.com/joho/godotenv/autoload"
	"golang.org/x/net/trace"
	r "gopkg.in/rethinkdb/rethinkdb-go.v6"
	"within.website/ln"
	"within.website/ln/ex"
	"within.website/mi/rethink"
	"within.website/mi/switchcounter"
	"within.website/x/web/useragent"
)

var (
	/*
		// Gitea
		giteaInstance = flag.String("gitea-instance", "", "Gitea instance to use")
		giteaAPIToken = flag.String("gitea-api-token", "", "Gitea API token")

		// Github
		githubToken = flag.String("github-token", "", "Github API token")
	*/

	// RethinkDB
	rethinkDBURL = flag.String("rethinkdb-url", "rethinkdb2://admin@127.0.0.1:28015/mi", "RethinkDB URL")

	// Port
	port   = flag.String("port", "5000", "HTTP port")
	domain = flag.String("domain", "mi.within.website", "domain this is being served on")

	// meta
	noPush = flag.Bool("no-push", false, "if set, don't push content")

	// switchcounter
	switchFile = flag.String("switch-file", "", "if set, import switches from CSV")
)

func main() {
	flagenv.Parse()
	flag.Parse()
	ln.AddFilter(ex.NewGoTraceLogger())

	http.DefaultTransport = useragent.Transport("mi-posse", "https://"+*domain+"/.within/botinfo", http.DefaultTransport)

	ctx := context.Background()

	session, err := rethink.GetSession(*rethinkDBURL)

	mastodonClient, err := makeMastodon()
	if err != nil {
		ln.FatalErr(ctx, err)
	}

	redditBot, err := makeReddit()
	if err != nil {
		ln.FatalErr(ctx, err)
	}

	twitterClient, err := makeTwitter()
	if err != nil {
		ln.FatalErr(ctx, err)
	}

	mux := http.NewServeMux()
	pm, err := MakeMiddleware(*pasetoPublicKey, *pasetoPrivateKey, mux)
	if err != nil {
		ln.FatalErr(ctx, err)
	}

	mux.Handle("/static/", http.FileServer(http.Dir(".")))
	mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "./static/index.html")
	})

	tok, err := pm.CreateToken(
		[][2]string{
			{"from", "main"},
		},
		time.Now().AddDate(2, 0, 0),
	)
	if err != nil {
		ln.FatalErr(ctx, err)
	}

	fmt.Printf("token: %s\n", tok)

	mi := &Mi{
		session:        session,
		mastodonClient: mastodonClient,
		twitterClient:  twitterClient,
		redditBot:      redditBot,
		mux:            mux,
	}
	mi.RegisterRoutes()
	sc := switchcounter.New(session, mux)

	mux.HandleFunc("/debug/requests", func(rw http.ResponseWriter, req *http.Request) {
		trace.Render(rw, req, true)
	})

	mux.HandleFunc("/debug/events", func(rw http.ResponseWriter, req *http.Request) {
		trace.RenderEvents(rw, req, true)
	})

	mux.HandleFunc("/.within/tokeninfo", func(rw http.ResponseWriter, req *http.Request) {
		tokenData := req.Context().Value(tokenKey)
		json.NewEncoder(rw).Encode(tokenData)
	})

	if *switchFile != "" {
		fin, err := os.Open(*switchFile)
		if err != nil {
			ln.FatalErr(ctx, err)
		}

		switches, err := sc.ImportCSV(fin)
		if err != nil {
			ln.FatalErr(ctx, err)
		}

		if len(switches) == 0 {
			panic("what")
		}

		err = r.Table("switches").Insert(switches).Exec(session)
		if err != nil {
			ln.FatalErr(ctx, err)
		}

		return
	}

	ctx, cancel := context.WithCancel(ctx)
	go func(cf func()) {
		var signalChan chan os.Signal
		signalChan = make(chan os.Signal, 1)
		signal.Notify(signalChan, os.Interrupt)

		<-signalChan
		cf()
	}(cancel)

	go mi.StreamMastodon(ctx)
	go mi.StreamReddit(ctx)

	if !*noPush {
		mi.RegisterPusher(mi.PushDiscordWebhook)
		mi.RegisterPusher(mi.PushReddit)
		mi.RegisterPusher(mi.PushMastodon)
		mi.RegisterPusher(mi.PushTwitter)
		go mi.StreamMastodonToTwitter(ctx)
		go mi.BlogPOSSE(ctx)
	}

	h := &http.Server{
		Addr: ":" + *port,
		Handler: GoTraceMiddleware{
			next: ex.HTTPLog(pm),
		},
	}

	go func() { ln.FatalErr(ctx, h.ListenAndServe()) }()

	<-ctx.Done()
	ln.Log(ctx, ln.Info("cleaning up"))
	time.Sleep(500 * time.Millisecond)
}