package main

import (
	"embed"
	"flag"
	"fmt"
	"go_dreamfactory/cmd/upgrade/tools"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"path"
	"sort"
	"strings"
	"time"

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

//go:embed views/*
var f embed.FS

var version = "0.0.1"

func main() {

	host := flag.String("host", "10.0.0.9", "Host")
	port := flag.String("port", "8080", "Port")
	uploadsDir := flag.String("uploadsDir", "./uploads", "上传文件存储地址")
	wwwDir := flag.String("wwwDir", "./www", "www服务地址，即解压地址")

	flag.Parse()

	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.Static("/prd", "./www")
	tmpl := template.Must(template.New("").ParseFS(f, "views/*"))
	r.SetHTMLTemplate(tmpl)

	r.GET("/version", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"version": version,
		})
	})

	r.GET("/", func(c *gin.Context) {
		fmt.Println(tmpl.DefinedTemplates())
		c.HTML(http.StatusOK, "index.html", nil)
	})

	r.GET("/upload", func(c *gin.Context) {
		fmt.Println(tmpl.DefinedTemplates())
		c.HTML(http.StatusOK, "upload.html", nil)
	})

	r.POST("/upload", func(c *gin.Context) {
		f, err := c.FormFile("file")
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		}

		//从上传的文件名获取到版本号
		s := strings.SplitN(f.Filename, "-", 2)
		if len(s) != 2 {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": "上传的文件名中没有包含版本号 eg. update.zip-0.0.1",
			})
			return
		}
		version = s[1] //设置版本号

		dst := path.Join(*uploadsDir, f.Filename)
		err = c.SaveUploadedFile(f, dst)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
		}
		_, err = tools.Unzip(dst, *wwwDir)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
		}

		c.JSON(http.StatusOK, gin.H{
			"msg": "upload success",
			"url": strings.Join([]string{"http://" + *host + ":" + *port, "/prd/", strings.Split(f.Filename, ".")[0], "/index.html"}, ""),
		})
	})

	r.GET("/dirs", func(c *gin.Context) {
		dir, err := ioutil.ReadDir(*wwwDir)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
		}

		type Item struct {
			Name     string `json:"name"`
			Url      string `json:"url"`
			DateTime string `json:"dateTime"`
		}

		var dirs []Item
		for _, f := range dir {
			// if f.IsDir() && len(f.Name()) > 0 && f.Name() != "__MACOSX" {
			dirs = append(dirs, Item{
				Name:     f.Name(),
				Url:      strings.Join([]string{"http://" + *host + ":" + *port, "/prd/", f.Name()}, ""),
				DateTime: f.ModTime().Format(time.RFC3339),
			})
			// }
		}

		// 排序
		sort.SliceStable(dirs, func(i, j int) bool {
			return dirs[i].DateTime > dirs[j].DateTime
		})

		c.JSON(http.StatusOK, gin.H{
			"dirs": dirs,
		})
	})

	// 同步配置
	// 接受客户端上传的文件覆盖服务器上文件
	r.POST("/sync", func(c *gin.Context) {
		f, err := c.FormFile("file")
		if err != nil {
			log.Print(err)
			return
		}
		if f.Filename!="config.json"{
			log.Print("上传的配置文件不是config.json")
			return
		}
		dst := path.Join(*wwwDir, f.Filename)
		err = c.SaveUploadedFile(f, dst)
		if err != nil {
			log.Print(err)
			return
		}
	})

	err := r.Run("0.0.0.0:" + *port)
	if err != nil {
		log.Fatal(err)
	}
}
