package db

import (
	"context"
	"database/sql"
	"ssp/constants"
	"ssp/logger"
	_ "mysql"
	"time"
)

/* *
 * Function to open a mysql database connection, or return the resource if already open */
func DbConnect() *sql.DB {
	db, err := sql.Open(constants.DbDriver, constants.DbUser+":"+constants.DbPass+"@"+constants.DbProtocal+"("+constants.DbHost+":"+constants.DbPort+")/"+constants.DbName)
	DbCheckErr(err)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	err = db.PingContext(ctx)
	DbCheckErr(err)
	return db
}

/* *
 * Function to pass a query to a database & get multi row
 * */
func DbQuery(query string, args ...interface{}) (*sql.Rows, error) {
	db := DbConnect()
	defer db.Close()
	Query, err := db.Query(query, args...)
	DbCheckErr(err)
	return Query, err
}

/* *
 * Function to pass a query to a database & get single row
 * */
func DbQueryRow(query string, args ...interface{}) *sql.Row {
	db := DbConnect()
	defer db.Close()
	QueryRow := db.QueryRow(query, args...)
	return QueryRow
}

/* *
 * Function to pass a query to a database link
 * */
func PrepareData(query string) (*sql.Stmt, error) {
	db := DbConnect()
	defer db.Close()
	Prepare, err := db.Prepare(query)
	DbCheckErr(err)
	return Prepare, err
}

/* *
 * Function to get number of rows of a query
 * */
func DbNumRows(query string) (int, error) {
	numrows, err := DbQuery(query)
	DbCheckErr(err)
	rowcount := 0
	for numrows.Next() {
		rowcount += 1
	}
	return rowcount, err
}

/* *
 * Function to check error
 * */
func DbCheckErr(err error) {
	if err != nil {
		logger.Log.Println(err.Error())
	}
}
