package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"path/filepath"
	"simple-web/core"
	"strings"

	_ "dev.hexasoftware.com/hxs/prettylog.git/global"
)

var (
	c = core.Demo()
)

// list users
func helloHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "application/json")
	s := c.Session()
	res := s.User().MustList()

	jenc := json.NewEncoder(w)
	jenc.SetIndent(" ", " ")
	jenc.Encode(res)

	// Lets list users and show them
}

// Create an handler that serves a file or if doesn not exists send it too index.html

func vserve() http.HandlerFunc {
	absPath, _ := filepath.Abs("public")
	log.Println("static:", absPath)

	return func(w http.ResponseWriter, r *http.Request) {
		lpath, err := filepath.Abs(filepath.Join("public", r.URL.Path[1:]))
		if err != nil || !strings.HasPrefix(lpath, absPath) {
			http.ServeFile(w, r, "public/index.html")
			return
		}
		if _, err := os.Stat(lpath); os.IsNotExist(err) {
			http.ServeFile(w, r, "public/index.html")
			return
		}
		http.ServeFile(w, r, lpath)
	}
}

func main() {
	// Do this in some cmd line
	s := c.Session()
	s.User().NewUser("admin", "Administration account", "admin@domain.tld", "1q2w3e")

	mux := http.NewServeMux()
	mux.HandleFunc("/api", helloHandler)

	if os.Getenv("DEVMODE") != "" {
		log.Println("Developer mode")
		u, _ := url.Parse("http://localhost:3000")
		mux.Handle("/", httputil.NewSingleHostReverseProxy(u))
	} else {
		log.Println("Production")
		mux.HandleFunc("/", vserve())
	}
	// Dev
	//mux.HandleFunc("/", proxyDev)
	// Prod

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Println("Server Starting at :", port)
	http.ListenAndServe(fmt.Sprintf(":%s", port), mux)

}
