package handlers

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/mux"
)

func recoveryMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			defer func() {
				if err := recover(); err != nil {
					log.Printf("error: panic while recovering from another panic: %v\n", err)
					fmt.Fprintf(w, "internal server error: %v\n", err)
				}
			}()

			if err := recover(); err != nil {
				log.Printf("error: %v\n", err)
				renderInternalServerError(w, r, err)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

func StartMainServer() {
	// Initialize Gorilla router
	router := mux.NewRouter()
	router.Use(recoveryMiddleware)
	router.HandleFunc("/", indexGetHandler).Methods("GET")
	router.HandleFunc("/", newPasteHandler).Methods("POST")
	router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}", viewPasteHandler).Methods("GET")
	router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}/nr", viewPasteHandlerNoRedirect).Methods("GET")
	router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}/meta", viewPasteHandlerMeta).Methods("GET")
	router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}", deletePasteHandler).Methods("DELETE")
	router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}/delete", deletePasteHandler).Methods("POST")

	srv := &http.Server{
		Handler:      router,
		Addr:         "127.0.0.1:8000",
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	log.Fatal(srv.ListenAndServe())
}