package ui

import (
	"fmt"
	"github.com/gliderlabs/ssh"
	"math/rand"
	"net/http"
	"regexp"
	"strconv"
	"strings"
)

func GenerateCLIExammples(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Error parsing form", http.StatusBadRequest)
		return
	}
	id := r.FormValue("rendez-vous-id")
	generatedId := false
	if id == "" {
		id = strconv.Itoa(rand.Int() % 1000000)
		generatedId = true
	}

	remoteShells := r.Form["remote-shell"]
	localShells := r.Form["local-shell"]
	keysString := r.FormValue("ssh-keys")
	access := getConvergeAccess(r)

	downloadCommand := r.FormValue("download-command")
	certificateValidation := r.FormValue("certificate-validation") != ""
	sshPublicKeys := strings.Split(keysString, "\n")
	usageInputs := NewUsageInputs(id, sshPublicKeys, remoteShells, localShells, downloadCommand,
		certificateValidation)
	if generatedId {
		usageInputs.ErrorMessages = append(usageInputs.ErrorMessages, "rendez-vous id is randomly generated, changes on every page refresh")
	}
	matched, _ := regexp.MatchString("^[a-zA-Z0-9-_]+$", id)
	if !matched {
		usageInputs.ErrorMessages = append(usageInputs.ErrorMessages, "ID may consist only of alphanumeric characters, '-', and '_'")
	}
	validPubKeys := 0
	for index, pubkey := range sshPublicKeys {
		pubkey = strings.TrimSpace(pubkey)
		if pubkey == "" {
			continue
		}
		_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubkey))
		if err != nil {
			keysummary := pubkey
			if len(pubkey) > 45 {
				keysummary = keysummary[:20] + " ... " + keysummary[len(pubkey)-20:]
			}
			usageInputs.ErrorMessages = append(usageInputs.ErrorMessages,
				fmt.Sprintf("ssh public key line %d: %s: %s", index+1, keysummary, err.Error()))
		} else {
			validPubKeys++
		}
	}
	if validPubKeys == 0 {
		usageInputs.ErrorMessages = append(usageInputs.ErrorMessages,
			"No valid public keys configured. Without these the agent will not work.")
	}

	err = ShellUsage(access, usageInputs).Render(r.Context(), w)
	if err != nil {
		http.Error(w, err.Error(), 500)
	}
}