package djdb

import (
    "context"
    "database/sql"
    "djconstants"
    "djlogger"
    _ "mysql"
    "sync"
    "time"
)

var (
    db   *sql.DB
    once sync.Once
)

/* *
* Function to get or initialize the database connection pool */
func DbConnect() *sql.DB {
    once.Do(func() {
        var err error
        db, err = sql.Open(djconstants.DbDriver, 
                djconstants.DbUser+":"+djconstants.DbPass+"@"+
                djconstants.DbProtocal+"("+djconstants.DbHost+":"+
                djconstants.DbPort+")/"+djconstants.DbName)
        DbCheckErr(err)
        
        // Configure connection pool
        db.SetMaxOpenConns(100)        // Max open connections
        db.SetMaxIdleConns(10)         // Max idle connections
        db.SetConnMaxLifetime(time.Hour) // Max connection lifetime
        
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        err = db.PingContext(ctx)
        DbCheckErr(err)
    })
    return db
}

/* *
* Function to pass a query to a database & get multi row
* IMPORTANT: Caller must close the returned rows with defer rows.Close()
* */
func DbQuery(query string, args ...interface{}) (*sql.Rows, error) {
    db := DbConnect()
    rows, err := db.Query(query, args...)
    if err != nil {
        DbCheckErr(err)
        return nil, err
    }
    return rows, nil
}

/* *
* Function to pass a query to a database & get single row
* */
func DbQueryRow(query string, args ...interface{}) *sql.Row {
    db := DbConnect()
    return db.QueryRow(query, args...)
}

/* *
* Function to pass a query to a database link
* IMPORTANT: Caller must close the returned statement with defer stmt.Close()
* */
func PrepareData(query string) (*sql.Stmt, error) {
    db := DbConnect()
    stmt, err := db.Prepare(query)
    if err != nil {
        DbCheckErr(err)
        return nil, err
    }
    return stmt, nil
}

/* *
* Function to get number of rows of a query
* */
func DbNumRows(query string) (int, error) {
    rows, err := DbQuery(query)
    if err != nil {
    	return 0, err
    }
    defer rows.Close() // Properly close rows
    
    rowcount := 0
    for rows.Next() {
    	rowcount++
    }
    return rowcount, rows.Err()
}

/* *
* Function to check error
* */
func DbCheckErr(err error) error {
    if err != nil {
        djlogger.Log.Println("MYSQL Error:", err)
        return err
    }
    return nil
}
