package model

import (
	"time"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB
var id1 uint = 0

func Init() {
	connectDatabase()
	var err error
	// insert auto-table
	err = DB.AutoMigrate(&Users{})
	if err != nil {
		logrus.Fatal(err)
	}
	err = DB.AutoMigrate(&content{})
	if err != nil {
		logrus.Fatal(err)
	}
}

func connectDatabase() {
	// config
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./")
	err := viper.ReadInConfig()
	if err != nil {
		logrus.Panic(err)
	}
	// connect to database
	logInfo := viper.GetStringMapString("mysql")
	sqlInfo := logInfo["user"] + ":" + logInfo["password"] +
		"@(localhost)/" + logInfo["database"] + "?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err = gorm.Open(mysql.Open(sqlInfo), &gorm.Config{})
	if err != nil {
		logrus.Panic(err)
	}
}

// Backcheck content through link
//通过链接反查内容
func findlink(_Route string) content {
	var p content
	err := DB.First(&p, "Route = ?", _Route)
	if err != nil {
		logrus.Error(err)
	}
	return p
}

// save text information
//保存文本和文件信息
func savetext(_Route string, _Time uint, _Passwd string,_Time1 time.Time) {
	id1++
	p := content{
		ID :      id1,
		Route:    _Route,
		Passwd:     _Passwd,
		Date:    time.Now(),
		Time1:   _Time1,
		Time2:   0,

	}
	DB.Create(&p)
}

// Check whether the number of visits exceeds the threshold and the time limit
//检查是否超过总访问次数和截止时间
func checkt(_Route string) {
	var p content
	err := DB.First(&p, "Route = ?",_Route)
	if err != nil {
		logrus.Error(err)
	}
	t := time.Now()
	p.Time2++
	if p.Time2 > p.Time||t.After(p.Time1) {
		DB.Delete(&p)
	}
}