package main

import (
	"ascend/nfccard/nfc"
	"fmt"
	"log"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func main() {
	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()
	corsConfig := cors.DefaultConfig()
	corsConfig.AllowAllOrigins = true
	r.Use(cors.New(corsConfig))

	r.GET("/getnfcid", getNfcCidHandler)
	r.POST("/writenfc", writeNfcHandler)

	if err := r.Run(":8088"); err != nil {
		log.Fatal(err)
	}
}

func getNfcCidHandler(c *gin.Context) {
	response, err := nfc.GetNfcId()
	if err != nil {
		c.JSON(200, gin.H{
			"code":  500,
			"error": err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"sid":  response,
	})
}

func writeNfcHandler(c *gin.Context) {
	//取得POST过来的数据
	data := c.PostForm("data")
	fmt.Println("data", data)

	_, err := nfc.WriteNfcCard(data)
	if err != nil {
		c.JSON(200, gin.H{
			"code":  500,
			"error": err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "寫入成功",
	})
}
