package jobs

import (
	"encoding/json"
	"gadmin/utility"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

var DownloadBackup = new(jDownloadBackup)

type jDownloadBackup struct{}

func (j *jDownloadBackup) Run() {
	//logrus.Info("jDownloadBackup Run.....")
	//if os.Getenv("GIN_MODE") != "release" {
	//	j.redisHistoryKeys()
	//} else {
	//	logrus.Warn("正式环境无需进行下载备份，跳过..")
	//}

}

// redisHistoryKeys redis历史key
func (j *jDownloadBackup) redisHistoryKeys() {

	var (
		downloadURL = os.Getenv("DOWNLOAD_BACKUP_URL") + RedisBackupPath  // 下载备份链接地址前缀
		savePath    = os.Getenv("DOWNLOAD_BACKUP_PATH") + RedisBackupPath // 下载保存路径
		sourceURL   = downloadURL + "download.json"                       // 拉取下载列表源
		jsonData    []string
	)

	utility.CreateDir(savePath) // 创建保存路径

	res, err := http.Get(sourceURL)
	defer res.Body.Close()
	if err != nil {
		logrus.Errorf("http.Get err:%v", err)
	}

	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		logrus.Errorf("ioutil.ReadAll err:%v", err)
	}

	if err = json.Unmarshal(data, &jsonData); err != nil {
		logrus.Errorf("json.Unmarshal err:%v", err)
	}

	for i := 0; i < len(jsonData); i++ {
		j.downLoadSaveResources(savePath, downloadURL+jsonData[i])
	}
}

func (j *jDownloadBackup) downLoadSaveResources(base string, url string) {

	pic := base
	idx := strings.LastIndex(url, "/")
	if idx < 0 {
		pic += "/" + url
	} else {
		pic += url[idx+1:]
	}
	v, err := http.Get(url)
	if err != nil {
		logrus.Errorf("Http get [%v] failed! %v", url, err)
		return
	}
	defer v.Body.Close()
	content, err := ioutil.ReadAll(v.Body)
	if err != nil {
		logrus.Errorf("Read http response failed! %v", err)
		return
	}
	err = ioutil.WriteFile(pic, content, 0666)
	if err != nil {
		logrus.Errorf("Save to file failed! %v", err)
		return
	}
	logrus.Info("Download and save successfully：", url)
	return
}
