package works

import (
	"log"
	"os"
	"time"

	"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
	"git.lxtend.com/lixiangwuxian/qqbot/util"
)

func init() {
	util.AddCycleTask("cleanTmpFolder", 5*time.Minute, 5*time.Minute, cleanTmpFolder)
	util.AddCycleTask("cleanDB", 1*time.Hour, 1*time.Hour, cleanDB)
}

func cleanTmpFolder() {
	//递归获取./tmp/目录下的所有文件
	files, err := os.ReadDir("./tmp/")
	if err != nil {
		log.Println(err)
		return
	}
	//删除创建时间超过5分钟的文件
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		info, _ := file.Info()
		if time.Since(info.ModTime()) > 5*time.Minute {
			os.RemoveAll(file.Name())
		}
	}
}

func cleanDB() {
	db := sqlite3.GetDB()
	now := time.Now()
	if now.Hour() == 1 && now.Minute() < 10 {
		start := time.Now()
		_, err := db.Exec("PRAGMA optimize")
		if err != nil {
			log.Printf("优化数据库失败: %v", err)
			return
		}
		log.Printf("数据库优化完成，耗时: %v", time.Since(start))
	}
}
