package main

import (
				"arimelody.me/arimelody.me/api/v1/music"

				"fmt"
				"html/template"
				"os"
				"net/http"
				"log"
				"strings"
        "time"
				"strconv"

				"github.com/gomarkdown/markdown"
				"github.com/gomarkdown/markdown/html"
				"github.com/gomarkdown/markdown/parser"
)

var mime_types = map[string]string{
				"css": "text/css; charset=utf-8",
				"png": "image/png",
				"jpg": "image/jpg",
				"webp": "image/webp",
				"html": "text/html",
				"asc": "text/plain",
				"pub": "text/plain",
				"js": "application/javascript",
}

var templates = template.Must(template.ParseFiles(
				"views/header.html",
				"views/footer.html",
				"views/index.html",
				"views/music.html",
				"views/music-gateway.html",
))

func log_request(req *http.Request, code int, start_time time.Time) {
				now := time.Now()
				difference := (now.Nanosecond() - start_time.Nanosecond()) / 1_000_000
				elapsed := "<1"
				if difference >= 1 {
								elapsed = strconv.Itoa(difference)
				}

				fmt.Printf("[%s] %s %s - %d (%sms) (%s)\n",
                now.Format(time.UnixDate),
                req.Method,
                req.URL.Path,
								code,
								elapsed,
                req.Header["User-Agent"][0],
        )
}

func web_handler(writer http.ResponseWriter, req *http.Request) {
				uri := req.URL.Path
				start_time := time.Now()

				if req.URL.Path == "/" {
								code := index_handler(writer, req)
								log_request(req, code, start_time)
								return
				}
				if uri == "/music" {
								code := music_handler(writer, req)
								log_request(req, code, start_time)
								return
				}
				if strings.HasPrefix(uri, "/music/") {
								code := music_gateway_handler(writer, req)
								log_request(req, code, start_time)
								return
				}
				code := static_handler(writer, req)
				log_request(req, code, start_time)
}

func index_handler(writer http.ResponseWriter, req *http.Request) int {
				err := templates.ExecuteTemplate(writer, "index.html", nil)
				if err != nil {
								http.Error(writer, err.Error(), http.StatusInternalServerError)
								return 500
				}
				return 200
}

func music_handler(writer http.ResponseWriter, req *http.Request) int {
				err := templates.ExecuteTemplate(writer, "music.html", music.QueryAllAlbums())
				if err != nil {
								http.Error(writer, err.Error(), http.StatusInternalServerError)
								return 500
				}
				return 200
}

func music_gateway_handler(writer http.ResponseWriter, req *http.Request) int {
				if len(req.URL.Path) <= len("/music/") {
								http.Error(writer, "400 bad request", http.StatusBadRequest)
								return 400
				}

				id := req.URL.Path[len("/music/"):]
				// http.Redirect(writer, req, "https://mellodoot.com/music/"+title, 302)
				// return
				album, ok := music.GetAlbum(id)
				if !ok {
								http.Error(writer, "404 not found", http.StatusNotFound)
								return 404
				}
				err := templates.ExecuteTemplate(writer, "music-gateway.html", album)
				if err != nil {
								http.Error(writer, err.Error(), http.StatusInternalServerError)
								return 500
				}
				return 200
}

func static_handler(writer http.ResponseWriter, req *http.Request) int {
				filename := "public/" + req.URL.Path[1:]

				// check the file's metadata
				info, err := os.Stat(filename)
				if err != nil {
								http.Error(writer, "404 not found", http.StatusNotFound)
								return 404
				}

				if len(req.Header["If-Modified-Since"]) > 0 && req.Header["If-Modified-Since"][0] != "" {
								if_modified_since_time, err := time.Parse(http.TimeFormat, req.Header["If-Modified-Since"][0])
								if err != nil {
												http.Error(writer, "400 bad request", http.StatusBadRequest)
												return 400
								}
								if req.Header["If-Modified-Since"][0] == info.ModTime().Format(http.TimeFormat) || if_modified_since_time.After(info.ModTime()) {
												writer.WriteHeader(304) // not modified
												return 304
								}
				}

				// set other nice headers
				writer.Header().Set("Cache-Control", "max-age=86400")
				writer.Header().Set("Last-Modified", info.ModTime().Format(http.TimeFormat))
				// Last-Modified: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
				// Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT

				// read the file
				body, err := os.ReadFile(filename)
				if err != nil {
								http.Error(writer, err.Error(), http.StatusInternalServerError)
								return 500
				}

				// setting MIME types
				filetype := filename[strings.LastIndex(filename, ".") + 1:]
				if mime_type, ok := mime_types[filetype]; ok {
								writer.Header().Set("Content-Type", mime_type)
				} else {
								writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
				}

				writer.Write([]byte(body))
				return 200
}

func parse_markdown(md []byte) []byte {
				extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
				p := parser.NewWithExtensions(extensions)
				doc := p.Parse(md)

				htmlFlags := html.CommonFlags
				opts := html.RendererOptions{ Flags: htmlFlags }
				renderer := html.NewRenderer(opts)

				return markdown.Render(doc, renderer)
}

func push_to_db_this_is_a_testing_thing_and_will_be_superfluous_later() {
				db := InitDatabase()

				for _, artist := range music.QueryAllArtists() {
								PushArtist(db, artist)
				}

				for _, album := range music.QueryAllAlbums() {
								PushAlbum(db, album)
				}

				defer db.Close()
}

func main() {
				push_to_db_this_is_a_testing_thing_and_will_be_superfluous_later()

				http.HandleFunc("/", web_handler)
				log.Fatal(http.ListenAndServe(":8080", nil))
}
