package main

import (
	"context"
	"git.wamblee.org/converge/pkg/comms"
	"git.wamblee.org/converge/pkg/models"
	templates2 "git.wamblee.org/converge/pkg/server/ui"
	"github.com/a-h/templ"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

type RenderFunc func() templ.Component

func render(dir string, name string, render RenderFunc) {
	fname := filepath.Join(dir, name)
	log.Printf("Writing to %s", fname)
	f, err := os.Create(fname)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	err = render().Render(context.Background(), f)
	if err != nil {
		panic(err)
	}
}

func main() {
	dir := "html/docs"

	netherlands, err := time.LoadLocation("Europe/Amsterdam")
	if err != nil {
		panic(err)
	}

	access := models.ConvergeAccess{
		Secure:   "s",
		BaseUrl:  "example.com",
		Location: netherlands,
	}

	fullindex := func() templ.Component {
		return templates2.Index(access)
	}
	usage := func() templ.Component {
		return templates2.UsageTab(access)
	}

	usageInputs := templates2.UsageInputs{
		Id:            "myid",
		SshKeys:       []string{"a", "b"},
		ErrorMessages: []string{},
		RemoteShells:  map[templates2.Shell]bool{templates2.POWERSHELL: true},
	}
	shellUsage := func() templ.Component {
		return templates2.ShellUsageTab(access, usageInputs)
	}

	render(dir, "fullindex.html", fullindex)
	render(dir, "index.html", templates2.AboutTab)
	render(dir, "usage.html", usage)
	render(dir, "shellusage.html", shellUsage)
	render(dir, "downloads.html", templates2.Downloads)

	render(dir, "sessions-none.html", func() templ.Component {
		return templates2.SessionsTab(nil, nil, netherlands)
	})
	render(dir, "sessions.html", func() templ.Component {

		japan, err := time.LoadLocation("Asia/Tokyo")
		if err != nil {
			panic(err)
		}

		state := models.NewState()
		agent := models.Agent{
			Guid:       models.AgentGuid(strconv.Itoa(rand.Int())),
			RemoteAddr: "10.220.1.3:3333",
			PublicId:   "id",
			StartTime:  time.Now().In(japan),
			EnvironmentInfo: comms.EnvironmentInfo{
				Username: "ci",
				Hostname: "container123",
				Pwd:      "/home/ci",
				OS:       "linux",
				Shell:    "/bin/bash",
			},
		}
		agent.SetExpiryTime(time.Now().In(japan).Add(10 * time.Minute))
		state.Agents[agent.Guid] = &agent
		client := models.Client{
			Guid:        models.ClientGuid(strconv.Itoa(rand.Int())),
			RemoteAddr:  models.RemoteAddr("10.1.3.3"),
			PublicId:    models.RendezVousId("c1"),
			AgentGuid:   models.AgentGuid("12342342"),
			ClientId:    models.ClientId("3"),
			StartTime:   time.Now().In(japan),
			SessionType: models.SessionType("sftp"),
		}
		state.Clients[client.Guid] = &client

		agents, clients := state.Slices()
		return templates2.SessionsTab(agents, clients, netherlands)
	})
}