package controllers

import (
	"bytes"
	"compress/zlib"
	"encoding/base64"
	"errors"
	"fmt"
	"goqs/models"
	"io"
	"net/http"
	"os/exec"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func NewResponse() models.Response {
	var res models.Response
	res.Init()
	return res
}

func Test(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"status": "ok"})
	cmd := exec.Command("bash", "-c", "cd /home/app/aimonkey && python3 main_run.py -package music.hising.live")
	err := cmd.Run()
	if err != nil {
		log.Error(err)
	}
}

func CheckErr(err error) models.Response {
	var res models.Response
	if err != nil {
		res.Code = 500
		res.Msg = err.Error()
	}
	return res
}

// 从表单获取分页参数
func getPage(c *gin.Context) models.Page {
	var p models.Page
	if err := c.ShouldBindQuery(&p); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		p.Index = 0
		p.Size = 0
		return p
	}
	fmt.Println(p)
	return p
}

func checkErr(err error) models.Response {
	var res models.Response
	if err != nil {
		res.Code = 500
		res.Msg = err.Error()
	}
	return res
}

func checkToken(c *gin.Context) (string, error) {
	if token, flag := c.GetQuery("token"); !flag {
		return "", errors.New("缺少token")
	} else if len(token) < 6 {
		return "", errors.New("token错误")
	} else {
		baseStr := token[3 : len(token)-2]
		baseByte, err := base64.StdEncoding.DecodeString(baseStr)
		if err != nil {
			return "", err
		}
		// fmt.Println(string(baseByte))
		return string(baseByte), nil
	}
}

func connClose(db *gorm.DB) {
	sqlDB, err := db.DB()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	sqlDB.Close()
}

//进行zlib压缩
func Compress(src []byte) []byte {
	var in bytes.Buffer
	w := zlib.NewWriter(&in)
	w.Write(src)
	w.Close()
	return in.Bytes()
}

//进行zlib解压缩
func UnCompress(compressSrc []byte) []byte {
	b := bytes.NewReader(compressSrc)
	var out bytes.Buffer
	r, _ := zlib.NewReader(b)
	io.Copy(&out, r)
	return out.Bytes()
}
