package main

import (
	"context"
	"git.wamblee.org/converge/pkg/comms"
	"git.wamblee.org/converge/pkg/models"
	templates2 "git.wamblee.org/converge/pkg/server/templates"
	"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[string]bool{templates2.POWERSHELL: true},
		LocalShells:   nil,
	}
	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, netherlands)
	})
	render(dir, "sessions.html", func() templ.Component {

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

		state := models.State{}
		agent := models.Agent{
			Guid:       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",
			},
			ExpiryTime: time.Now().In(japan).Add(10 * time.Minute),
		}
		state.Agents = append(state.Agents, agent)
		client := models.Client{
			Guid:        strconv.Itoa(rand.Int()),
			RemoteAddr:  "10.1.3.3",
			PublicId:    "c1",
			AgentGuid:   "12342342",
			ClientId:    "3",
			StartTime:   time.Now().In(japan),
			SessionType: "sftp",
		}
		state.Clients = append(state.Clients, client)
		return templates2.SessionsTab(&state, netherlands)
	})
}