package controllers

import (
	"bot/src/models"
	"database/sql"
	"fmt"
	"log"
	"math/rand"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

type DataController struct{ DB *sql.DB }

func NewDB(config models.Config) *DataController {
	dbaddr := fmt.Sprintf("%s:%s@tcp(%s)/%s", config.UserName, config.Password, config.HostName, config.DbName)

	db, err := sql.Open("mysql", dbaddr)
	if err != nil {
		panic(err)
	}

	db.SetConnMaxLifetime(time.Minute * 3)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)

	return &DataController{DB: db}
}

func RandRange() int {
	rand.Seed(time.Now().UnixNano())
	return rand.Intn(21) - 5
}

// UpdateUser updates user's dick size and checks if it's blocked
func (d *DataController) ClearAllBlocked() {
	_, err := d.DB.Exec("UPDATE users SET blocked = false")
	if err != nil {
		log.Fatal(err)
	} else {
		log.Println("Clear block stats complete")
	}
}

// CreateUser creates new user with random dick size and sets it to blocked
func (d *DataController) CreateUser(id int64, lname string, fname string) {
	_, err := d.DB.Exec("INSERT INTO users (id, fname, lname, dick_size, admin, blocked, trick) VALUES (?,?,?,?,?,?,?)", id, fname, lname, 0, 0, 0, 1)
	if err != nil {
		log.Fatal(err)
	} else {
		log.Printf("User %d created", id)
	}
}

// GetUser gets user's data by id
func (d *DataController) GetUser(id int64) *models.User {
	var user models.User
	row, err := d.DB.Query("SELECT * FROM users WHERE id =?", id)
	if err != nil {
		log.Fatal(err)
	}

	for row.Next() {
		err := row.Scan(&user.ID, &user.FirstName, &user.LastName, &user.DickSize, &user.Admin, &user.Blocked, &user.Trick)
		if err != nil {
			log.Fatal(err)
		}
	}

	return &user
}

// UpdateUser updates user's dick size and blocked status
func (d *DataController) UpdateDick(id int64, newDickSize int) {
	_, err := d.DB.Exec("UPDATE users SET dick_size =?, blocked =?, trick =? WHERE id =?", newDickSize, 1, +1, id)
	if err != nil {
		log.Fatal(err)
	} else {
		log.Printf("User %d dick size updated", id)
	}
}

// GetTopUsers gets top 10 users by dick size
func (d *DataController) GetTopUsers() []models.User {
	var users []models.User
	rows, err := d.DB.Query("SELECT * FROM users ORDER BY dick_size DESC LIMIT 10")
	if err != nil {
		log.Fatal(err)
	}

	for rows.Next() {
		var user models.User
		err := rows.Scan(&user.ID, &user.FirstName, &user.LastName, &user.DickSize, &user.Blocked, &user.Admin, &user.Trick)
		if err != nil {
			log.Fatal(err)
		}
		users = append(users, user)
	}

	return users
}
