package main

import (
	"bytes"
	"fmt"
	"git.kuschku.de/justJanne/bahn-api"
	"git.kuschku.de/justjanne/stateless-matrix-bot/api"
	"html/template"
	"math/rand/v2"
	"net/http"
	"net/url"
	"os"
	"strings"
)

func main() {
	var err error

	pushUrl, err := url.Parse(os.Getenv("BOT_PUSHURL"))
	if err != nil {
		panic(err)
	}
	bot := NewMatrixBot(pushUrl)

	// !8ball handler
	bot.HandleFunc("!8ball", func(bot *MatrixBot, notification api.Notification) error {
		positive := []string{
			"It is certain",
			"It is decidedly so",
			"Without a doubt",
			"Yes – definitely",
			"You may rely on it",
			"As I see it, yes",
			"Most Likely",
			"Outlook good",
			"Yes",
			"Signs point to yes.",
		}
		negative := []string{
			"Don’t count on it",
			"My reply is no",
			"My sources say no",
			"Outlook not so good",
			"very doubtful",
		}
		neutral := []string{
			"Reply hazy",
			"try again",
			"Ask again later",
			"Better not tell you now",
			"Cannot predict now",
			"Concentrate and ask again",
		}
		var answers []string
		switch rand.IntN(3) {
		case 0:
			answers = positive
			break
		case 1:
			answers = negative
			break
		case 2:
			answers = neutral
			break
		}
		answer := answers[rand.IntN(len(answers))]

		err = api.SendMessage(*bot.token, notification.RoomId, api.MessageContent{
			Body:    answer,
			MsgType: "m.text",
		})
		return nil
	})

	// !trains handler
	bahnTpl, err := template.New("bahn").Parse(`{{- /*gotype: bahn.Timetable*/ -}}
<b>{{.Station}}</b> Abfahrten
{{- range .Stops -}}
    {{- if .Departure -}}
        {{- if .Departure.Line -}}
        <li>{{- if .Departure.ChangedTime -}}{{.Departure.ChangedTime}}{{- else if .Departure.PlannedTime -}}{{.Departure.PlannedTime}}{{- end -}}
            · <b>{{ .Departure.Line }}</b></li>
        {{- else if .TripLabel.TripCategory -}}
            {{- if .TripLabel.TripNumber -}}
                <li>{{- if .Departure.ChangedTime -}}{{.Departure.ChangedTime}}{{- else if .Departure.PlannedTime -}}{{.Departure.PlannedTime}}{{- end -}}
                    · <b>{{ .TripLabel.TripCategory }} {{ .TripLabel.TripNumber }}</b></li>
            {{- end -}}
        {{- end -}}
    {{- end -}}
{{- end -}}`)
	if err != nil {
		panic(err)
	}
	bot.HandleFunc("!trains", func(bot *MatrixBot, notification api.Notification) error {
		elements := strings.SplitN(strings.TrimSpace(notification.Content.Body), " ", 3)
		response, err := http.Get(fmt.Sprintf("https://iris.noncd.db.de/iris-tts/timetable/fchg/%s", elements[1]))
		if err != nil {
			return err
		}
		timetable, err := bahn.TimetableFromReader(response.Body)
		if err != nil {
			return err
		}
		buf := new(bytes.Buffer)
		err = bahnTpl.Execute(buf, timetable)
		if err != nil {
			return err
		}
		err = api.SendMessage(*bot.token, notification.RoomId, api.MessageContent{
			FormattedBody: buf.String(),
			Format:        "org.matrix.custom.html",
			MsgType:       "m.text",
		})
		return nil
	})
	err = bot.Login(os.Getenv("BOT_USERNAME"), os.Getenv("BOT_PASSWORD"), os.Getenv("BOT_DEVICEID"))
	if err != nil {
		panic(err)
	}
	err = bot.RegisterPusher()
	if err != nil {
		panic(err)
	}
	go bot.RefreshTask()
	bot.Serve(":8080")
}