package model

import (
	//"fmt"
	"time"
    "math/rand"

	"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(&Content{})
	if err != nil {
		logrus.Fatal(err)
	}
	err = DB.AutoMigrate(&Users{})
	if err != nil {
		logrus.Fatal(err)
	}
    err = DB.AutoMigrate(&Url{},&Sid{})
	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(_url string) string {
	var p Content
	err := DB.First(&p, "Url1 = ?", _url)
	if err != nil {
		logrus.Error(err)
	}
	return p.Route
}

// save text information
//保存文本和文件信息
func Savetext(_Route string, _Time uint, _Passwd string,_Time1 time.Time,_url string) {
	id1++
	p := Content{
		ID :      id1,
		Route:    _Route,
		Time:     _Time,
		Passwd:     _Passwd,
		Date:    time.Now(),
		Time1:   _Time1,
		Time2:   0,
        Url1: _url,
	}
	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)
	}
}

//查找sessionid和url是否关联
func Find(sid string,_url string) bool {
	var url Url
	err1 := DB.First(&url, "Url1 = ?",_url).Error
	//fmt.Println(url.Url1,url.ID,"\n")
	if err1 != nil {
		return false
	}
	var sid1 Sid
	DB.Model(&url).Where("S = ?",sid).Association("User1").Find(&sid1)
	if sid1.UrlID == 0 {
		return false
	}
	return true
}

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789")

//随机生成字符串
func randStr(n int) string {
	rand.Seed(time.Now().Unix())
    b := make([]rune, n)
    for i := range b {
        b[i] = letters[rand.Intn(len(letters))]
    }
    return string(b)
}

//新建用户
func Createuser(_User Users) {
      _User.SessionId=randStr(8)
	  DB.Create(&_User)
}

//新建链接
func Createlink(sid string , _passwd string , _url string) bool {
	var p Content
	DB.First(&p, "Url1 = ?", _url)
	if p.Passwd == _passwd {
		 var p1 Sid
		 var p2 Url
		 p1.S = sid
		 err := DB.First(&p2,"Url1 = ?",_url).Error
		// fmt.Println("yes  ",err)
		 if err != nil {
			//fmt.Println("yes  ")
		    p2.Url1 = _url
			DB.Create(&p2)
		 }
		 DB.Model(&p2).Association("User1").Append(&p1)
         return true
	}
	return false
}
