package database

import (
	"context"
	"database/sql"
	"fmt"
	_ "github.com/lib/pq"
	"github.com/sirupsen/logrus"
	"shiny-pancake/internal/model"
)

const datetime = `2006-01-02T15:04:05Z`
const date = `2006-01-02`

type Database struct {
	conn *sql.DB
	log *logrus.Logger
	ctx  context.Context
}

func New(c *model.HostDetails) *Database {
	var db Database
	var h string
	var u string
	var pw string
	var dbn string
	var psqlInfo string
	var log *logrus.Logger
	h = c.Hostname
	u = c.Username
	pw = c.Secret
	dbn = c.DatabaseName

	db.ctx = context.Background()
	db.log = log
	psqlInfo = fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		h, 5432, u, pw, dbn)
	dbC, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		log.Fatalf("database.new: Cannot establish connection to %s: %v", h, err)
	}
	db.conn = dbC
	return &db
}


func (db *Database) UserSessions() ([]*model.Session, error) {
	query := `select usename, count(usename) from pg_stat_activity where usename is not null group by usename`

	rows, err := db.conn.Query(query)
	if err != nil {
		// handle this error better than this
		panic(err)
	}
	sessions := make([]*model.Session, 0)
	defer rows.Close()
	for rows.Next() {
		var sessCount model.Session
		err = rows.Scan(&sessCount.Username, &sessCount.Count)

		if err != nil {
			// handle this error
			panic(err)
		}
		sessions = append(sessions, &sessCount)

	}
	// get any error encountered during iteration
	err = rows.Err()
	if err != nil {
		panic(err)
	}


	return sessions, err
}