package main

import (
	"fmt"
	"io"
	"os"
	"path"
	"regexp"
	"sparrow/pkg/server"
	"sparrow/pkg/utils"
	"strconv"

	"github.com/kataras/iris"
)

func registerRouter(app *iris.Application) {
	app.Post("/upload_file", iris.LimitRequestBodySize(int64(*conMaxSize)),
		func(ctx iris.Context) {
			file, info, err := ctx.FormFile("file")
			if err != nil {
				server.Log.Error(err)
				ctx.JSON(map[string]interface{}{
					"code":    -1,
					"message": "文件大小超过限制(" + strconv.Itoa(*conMaxSize) + "字节)",
				})
				return
			}
			defer file.Close()
			fname := info.Filename
			fileSuffix := path.Ext(fname)
			re := regexp.MustCompile(*conAllowExt)
			if !re.MatchString(fileSuffix) {
				server.Log.Errorf("%s", "非法的文件格式"+fileSuffix)
				ctx.JSON(map[string]interface{}{
					"code":    -2,
					"message": "非法的文件格式",
				})
				return
			}
			newname := fmt.Sprintf("%s%s", utils.UUID(), fileSuffix)
			newfile := "./upload/tmp/" + newname
			utils.CreateIfNotExist(newfile)
			out, err := os.OpenFile(newfile,
				os.O_WRONLY|os.O_CREATE, 0666)

			if err != nil {
				ctx.JSON(map[string]interface{}{
					"code":    -3,
					"message": "文件上传失败:" + err.Error(),
				})
				return
			}
			defer out.Close()
			io.Copy(out, file)
			var fileURL string
			if *conDomain == "" {
				fileURL = "http://" + server.GetHTTPHost() + "/upload/tmp/" + newname
			} else {
				fileURL = *conDomain
			}
			ctx.JSON(map[string]interface{}{
				"code":    0,
				"message": "success",
				"file":    fileURL,
			})
			return
		})
}
