package file

import (
	"fmt"
	"mini_server/internal/config"
	"mini_server/internal/dao"
	"mini_server/internal/server/help"
	"net/http"

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

type DownloadURI struct {
	FileId string `uri:"file_id" binding:"len=32"`
}

// 文件下载接口
func Download(c *gin.Context) {
	var param DownloadURI
	if err := c.ShouldBindUri(&param); err != nil {
		c.JSON(http.StatusBadRequest, fmt.Sprintf("invalid download uri,err:%v", err))
		return
	}

	fileId := param.FileId
	var data *dao.File
	var err error
	var ok bool

	if config.FileCacheEnable { // 从文件缓存中查询
		if data, ok = help.GetFileCache(fileId); ok {
			logrus.Tracef("从内存缓存中获取文件数据，file_uuid:%v", fileId)
		}
	}

	if data == nil { // 未获取到文件缓存数据
		logrus.Tracef("从msyql中获取文件数据，file_uuid:%v", fileId)
		data, err = dao.File_Query(param.FileId)
		if err != nil {
			logrus.Errorf("文件下载失败,fileId:%s,err:%v", param.FileId, err)
			c.JSON(http.StatusInternalServerError, "文件下载失败")
			return
		}
		if data == nil { // 文件不存在
			logrus.Errorf("文件下载失败，文件file_id:%v不存在", param.FileId)
			c.JSON(http.StatusNotFound, "文件不存在")
			return
		}

		if config.FileCacheEnable { // 更新到文件缓存中
			help.SetFileCache(fileId, data)
		}
	}

	logrus.Tracef("文件%s下载成功，文件大小:%d，数据库中blob实际大小:%d", data.FileName, data.FileSize, len(data.FileContent))
	c.Header("Content-Disposition", "attachment;filename="+data.FileName)
	c.Header("Content-Type", data.FileType)
	c.Header("Accept-Length", fmt.Sprintf("%d", data.FileSize))
	c.Writer.WriteHeader(http.StatusOK)
	c.Writer.Write(data.FileContent)
}
