package main

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"

	"code.justin.tv/d8a/pg-healthcheck/common"
)

func NewBackend(host string, port int, database string, user string, pass string) common.BackendChecker {
	dsn := fmt.Sprintf("sslmode=disable host=%v port=%v dbname='%v' binary_parameters=yes", host, port, database)
	if user != "" {
		dsn = fmt.Sprintf("%v user=%v", dsn, user)
	}
	if pass != "" {
		dsn = fmt.Sprintf("%v password=%v", dsn, pass)
	}

	be := new(backend)
	be.dsn = dsn
	return be
}

type backend struct {
	dsn string
}

func (be *backend) Check() (string, error) {
	db, err := be.Open()
	if err != nil {
		//sm.MarkPortDown(be.port, "Unable to connect")
		return "", err
	}
	defer common.CloseResource(db)
	rows, err := db.Query("select 1")
	if err != nil {
		//sm.MarkPortDown(be.port, "Unable to query")
		return "", err
	}
	defer common.CloseResource(rows)
	for rows.Next() {
		// XXX AGB: Check result? 2015-01-06
	}
	return "Healthy", nil
}

func (be *backend) Open() (*sql.DB, error) {
	return sql.Open("postgres", be.dsn)
}
