package cmd

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"strings"

	"code.icod.de/postfix/manager/ent"
	"code.icod.de/postfix/manager/ui"
	"code.icod.de/postfix/manager/ui/handler"
	"git.icod.de/dalu/ginpongo2/v5"
	"github.com/flosch/pongo2/v5"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

const (
	prefixTCP  = "tcp:"
	prefixUNIX = "unix:"
)

var (
	uiDebug bool
	uiAddr  string
)

// uiCmd represents the ui command
var uiCmd = &cobra.Command{
	Use:   "ui",
	Short: "serves the management ui over http",
	RunE: func(cmd *cobra.Command, args []string) error {
		if !uiDebug {
			gin.SetMode(gin.ReleaseMode)
		}
		r := gin.Default()
		r.SecureJsonPrefix(")]}',\n")
		r.MaxMultipartMemory = 8 << 20
		if uiDebug {
			fmt.Println("debug mode")
			fl, e := pongo2.NewLocalFileSystemLoader("ui/templates/")
			if e != nil {
				return e
			}
			hr := ginpongo2.New(true, fl)
			r.HTMLRender = hr
		} else {
			fmt.Println("release mode")
			subFS, e := fs.Sub(ui.Templates, "templates")
			if e != nil {
				return e
			}
			fl := pongo2.NewFSLoader(subFS)
			hr := ginpongo2.New(false, fl)
			r.HTMLRender = hr
		}

		// Database
		client, e := ent.Open("mysql", "dev:dev@tcp(localhost:3306)/postfix")
		if e != nil {
			return e
		}
		defer client.Close()
		handler.SetClient(client)

		// Static
		r.Static("/assets/", "./assets/")

		r.GET("/", handler.GETIndex)

		// serve
		if strings.HasPrefix(uiAddr, prefixTCP) {
			addr := strings.TrimPrefix(uiAddr, prefixTCP)
			fmt.Println("listening on", addr)
			return r.Run(addr)
		} else if strings.HasPrefix(uiAddr, prefixUNIX) {
			addr := strings.TrimPrefix(uiAddr, prefixUNIX)
			if _, e := os.Stat(addr); errors.Is(e, os.ErrNotExist) {
				fmt.Println("listening on", addr)
				return r.RunUnix(addr)
			} else {
				if e := os.Remove(addr); e != nil {
					return e
				} else {
					fmt.Println("listening on", addr)
					return r.RunUnix(addr)
				}
			}
		} else {
			return nil
		}
	},
}

func init() {
	rootCmd.AddCommand(uiCmd)
	uiCmd.Flags().BoolVar(&uiDebug, "debug", false, "enable dev mode")
	uiCmd.Flags().StringVar(
		&uiAddr,
		"addr",
		"tcp:localhost:8080",
		"either tcp: or unix: e.g. tcp:localhost:3030 unix:/tmp/listen.sock",
	)
}
