package hdx

import (
	"fmt"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

type DB struct {
	db *sqlx.DB
}

func NewDB(dbhost, dbname, dbuser string) (*DB, error) {
	var err error
	config := fmt.Sprintf(
		"user=%s dbname=%s host=%s sslmode=disable",
		dbuser,
		dbname,
		dbhost,
	)
	db, err := sqlx.Connect(
		"postgres",
		config,
	)
	if err != nil {
		return nil, err
	}

	d := &DB{db}
	err = d.initializeDB()
	return d, err
}

func (d *DB) initializeDB() error {
	// XXX ignoring errors
	_, err := d.db.Exec(createdb)
	return err

}

func (d *DB) getcount(ip string) (int, error) {
	result := 0
	row := d.db.QueryRow("SELECT COUNT(*) FROM ips WHERE ip = $1",
		ip,
	)

	err := row.Scan(&result)
	if err != nil {
		return 0, err
	}
	return result, nil
}
