package model

import (
	"time"

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

var DB *gorm.DB

func Init() {}

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(name string) string {
	var p Users
	err := DB.First(&p, "Route = ?", name)
	if err != nil {
		logrus.Error(err)
	}
	return p.Name
}

// save text information
func savetext(_username string, s string, t1 time.Time) {
	p := Users{
		Username: _username,
		Name:     s,
		Date:     time.Now(),
		Time1:    t1,
	}
	DB.Create(&p)
	p1 := content{
		Name: s,
		Time: 0,
	}
	DB.Create(&p1)
}

// Check whether the number of visits exceeds the threshold
func checkt(s string) {
	var p content
	err := DB.First(&p, "Route = ?", s)
	if err != nil {
		logrus.Error(err)
	}
	p.Time++
	if p.Time > 200 {
		DB.Delete(&p)
	}
}

// Check whether the number of visits exceeds the time limit
func checkt1(s string) {
	var p []Users
	DB.Find(&p)
	for i := 0; i < len(p); i++ {
		t := time.Now()
		if p[i].Time1.After(t) {
			DB.Delete(&p)
		}
	}
}
