package main

import (
	"database/sql"
	"fmt"
	"net/http"
	"os"
	"strings"

	_ "github.com/lib/pq"
)

func main() {
	db, err := sql.Open("postgres", os.Getenv("DATABASE_CONNECTION_STRING"))
	if err != nil {
		panic(err)
	}

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		rows, err := db.Query(`SELECT id, alias, title FROM "Notes" WHERE alias IS NOT NULL AND "permission" IN ('freely', 'editable', 'limited') ORDER BY "createdAt" DESC`)
		if err != nil {
			w.WriteHeader(http.StatusServiceUnavailable)
			fmt.Fprintln(os.Stderr, err)
			return
		}
		defer rows.Close()

		w.Header().Add("Content-Type", "text/html")
		w.WriteHeader(http.StatusOK)

		_, _ = fmt.Fprintln(w, "<html>")
		_, _ = fmt.Fprintln(w, "<ul>")
		for rows.Next() {
			var id, title, alias string
			err = rows.Scan(&id, &alias, &title)
			if err != nil {
				w.WriteHeader(http.StatusServiceUnavailable)
				fmt.Fprintln(os.Stderr, err)
				return
			}
			// fmt.Println(id, alias)

			url := strings.TrimSuffix(os.Getenv("HEDGEDOC_URL"), "/") + "/" + alias
			_, _ = fmt.Fprintln(w, "<li>")
			_, _ = fmt.Fprintf(w, `%s (<a href="%s">%s</a>)`, title, url, url)
			_, _ = fmt.Fprintln(w, "</li>")
		}
		_, _ = fmt.Fprintln(w, "</ul>")
		_, _ = fmt.Fprintln(w, "</html>")
	})

	fmt.Fprintln(os.Stderr, "listening on :8080")
	err = http.ListenAndServe(":8080", http.DefaultServeMux)
	if err != nil {
		panic(err)
	}
}
