package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"os/exec"
)

type MimeType struct {
	Source       string   `json:"source"`
	Extensions   []string `json:"extensions"`
	Compressible bool     `json:"compressible"`
	Charset      string   `json:"charset"`
}

type Data map[string]MimeType

func main() {
	out, err := os.OpenFile("generated_mime_types.go", os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		panic(err)
	}

	defer out.Close()

	rsp, err := http.Get("https://cdn.rawgit.com/jshttp/mime-db/v1.33.0/db.json")
	if err != nil {
		panic(err)
	}

	if rsp.StatusCode != http.StatusOK {
		panic(rsp)
	}

	var result Data

	if err := json.NewDecoder(rsp.Body).Decode(&result); err != nil {
		panic(err)
	}

	fmt.Fprintln(out, "package mimedb")
	fmt.Fprintln(out, "")
	fmt.Fprintln(out, "var (")
	fmt.Fprintln(out, "	mimeTypeToExts = map[string][]string{")

	for mimeType, entry := range result {
		if len(entry.Extensions) > 0 {
			fmt.Fprintf(out, "		%q: %#v,\n", mimeType, entry.Extensions)
		}
	}

	fmt.Fprintln(out, "	}")
	fmt.Fprintln(out, ")")

	if err := out.Close(); err != nil {
		panic(err)
	}

	// run `go fmt` on the output
	if err := exec.Command("go", "fmt").Run(); err != nil {
		panic(err)
	}
}
