package main

import (
	"log"
	"net/http"

	"github.com/kabukky/httpscerts"
)

func main() {

	http.HandleFunc("/alter-password/", alterPasswordHandler)

	err := httpscerts.Generate("cert.pem", "key.pem", "127.0.0.1:8000")
	if err != nil {
		log.Fatal("Error: Couldn't create https certs.")
	}

	log.Fatal(http.ListenAndServeTLS(":8000", "cert.pem", "key.pem", nil))
}

func alterPasswordHandler(res http.ResponseWriter, req *http.Request) {
	if req.Method == http.MethodOptions {
		res.Header().Set("Access-Control-Allow-Origin", "https://localhost:8000")
		res.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		res.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		res.Header().Set("Access-Control-Allow-Credentials", "true")
		res.WriteHeader(http.StatusOK)
		return
	} else if req.Method == http.MethodGet {
		body := `
		<html>
		<body>
			<form method="post">
				<label for="password">Password</label>
				<input id="password" type="password" placeholder="Password" required>
				<label for="repeatPassword">Repeat Password</label>
				<input id="repeatPassword" type="password" placeholder="Repeat Password" required>
				<button type="submit">Change Password</button>
			</form>
		</body>
		</html>
		`
		res.WriteHeader(http.StatusOK)
		res.Header().Set("Content-Type", "text/html")
		res.Write([]byte(body))
	} else if req.Method == http.MethodPost {
		err := req.ParseForm()
		log.Println(err, req.Form)
	}
}
