package main

import (
	"log"
	"net/http"
	"runtime"

	"regexp"
	"strconv"

	"git.satori.love/gameui/webp/models"
	_ "github.com/go-sql-driver/mysql"
)

func init() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

// string 转换为 int, 如果转换失败则返回默认值
func stringToInt(str string, defaultValue int) int {
	if str == "" {
		return defaultValue
	}
	value, err := strconv.Atoi(str)
	if err != nil {
		return defaultValue
	}
	return value
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	var mysqlConnection models.MysqlConnection
	mysqlConnection.Init()

	// URL 格式: /img/{type}/{id}.{format}?width=320&height=320&fit=cover
	http.HandleFunc("/img/", func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.Method, r.URL.Path)
		reg := regexp.MustCompile(`^/img/([0-9a-zA-Z]+)/([0-9a-zA-Z]+).(jpg|jpeg|png|webp)$`)
		matches := reg.FindStringSubmatch(r.URL.Path)
		if len(matches) != 4 {
			log.Println("URL 格式错误", matches)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		group, id, format, width, height, fit := matches[1], matches[2], matches[3], stringToInt(r.URL.Query().Get("width"), 0), stringToInt(r.URL.Query().Get("height"), 0), r.URL.Query().Get("fit")
		content, err := mysqlConnection.GetImageContent(group, id)
		if err != nil {
			log.Println("获取图片失败", format, err)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		var img models.Image
		img.Init(content)
		data, err := img.ToWebP(width, height, fit)
		if err != nil {
			log.Println("转换图片失败", err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		w.Header().Set("Content-Type", "image/webp")
		w.Header().Set("Cache-Control", "max-age=31536000")
		w.Write(data)
	})

	// URL 格式: /webp/{type}-{id}-{version}-{width}-{height}-{fit}.{format}
	http.HandleFunc("/webp/", func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.Method, r.URL.Path)
		reg := regexp.MustCompile(`^/webp/([0-9a-zA-Z]+)-([0-9a-zA-Z]+)-([0-9a-zA-Z]+)-([0-9]+)-([0-9]+)-([a-zA-Z]+).(jpg|jpeg|png|webp)$`)
		matches := reg.FindStringSubmatch(r.URL.Path)
		if len(matches) != 4 {
			log.Println("URL 格式错误", matches)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		group, id, version, width, height, fit, format := matches[1], matches[2], matches[3], stringToInt(matches[4], 0), stringToInt(matches[5], 0), matches[6], matches[7]
		content, err := mysqlConnection.GetImageContent(group, id)
		if err != nil {
			log.Println("获取图片失败", version, format, err)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		var img models.Image
		img.Init(content)
		data, err := img.ToWebP(width, height, fit)
		if err != nil {
			log.Println("转换图片失败", err)
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		w.Header().Set("Content-Type", "image/webp")
		w.Header().Set("Cache-Control", "max-age=31536000")
		w.Write(data)
	})

	log.Println("Server is running at http://localhost:6001")
	http.ListenAndServe(":6001", nil)
}
