package database

import (
	"fmt"
	"os"
	"time"

	"github.com/asdine/storm"
	"github.com/rs/zerolog"
)

// OpenDB returns a new database object, from opening existing db
func OpenDB(dbPath string, log *zerolog.Logger, version string) (*DB, error) {
	var db DB
	var err error
	databaseLogger := log.With().Str("module", "database").Logger() // Setting up a sub logger for the database module
	db.Logger = &databaseLogger
	db.DB, err = storm.Open(dbPath)
	if err != nil {
		db.Err(err).Msg("No existing database found. this does not appear to be a repo, please init repo")
		return &db, err
	}
	defer db.Close()
	return &db, nil
}

// CreateDB sets up bolt and Storm according to the path of the database //TODO: Save a backup of the config in DB on creation
func CreateDB(dbPath string, version string, repoName string) error {
	db, err := storm.Open(dbPath)
	if err != nil {
		fmt.Println("error initializing database")
		return err
	}
	defer db.Close()
	fmt.Println("Initializing new database..")
	initTime := time.Now().String()
	var gvcInit GVCInfo
	gvcInit.InitTime = initTime
	gvcInit.GVCVersion = version
	gvcInit.RepoName = repoName
	if err := db.Save(&gvcInit); err != nil {
		fmt.Println("Unable to init db")
		return err
	}
	return nil
}

// CheckDB checks to see if database exists
func CheckDB(dbPath string) error {
	if _, err := os.Stat(dbPath); os.IsNotExist(err) {
		return err
	}
	return nil
}
