package noodle

import (
	"log"

	"github.com/google/uuid"
	"go.mills.io/bitcask/v2"
)

type Database struct {
	connection *bitcask.Bitcask
	Handle     *bitcask.Collection
}

func NewDatabase(path string) *Database {
	db, err := bitcask.Open(path)
	if err != nil {
		log.Fatal(err)
	}
	return &Database{
		connection: db,
		Handle:     db.Collection("noodles"),
	}
}

func (db *Database) MakeID() string {
	id, err := uuid.NewUUID()
	if err != nil {
		log.Print(err)
		return ""
	}
	return id.String()
}

func (db *Database) GetAll() []Noodle {
	var data []Noodle
	if err := db.Handle.List(&data); err != nil {
		log.Print(err)
		return nil
	}
	return data
}

func (db *Database) GetAllGeneric() []interface{} {
	var data []interface{}
	if err := db.Handle.List(&data); err != nil {
		log.Print(err)
		return nil
	}
	return data
}

func (db *Database) Get(id string) Noodle {
	var item Noodle
	log.Printf("Looking up noodle key='%s'", id)
	log.Printf("key='%s' exists=%t", id, db.Handle.Has(id))
	if err := db.Handle.Get(id, &item); err != nil {
		log.Print(err)
		return Noodle{}
	}
	return item
}

func (db *Database) Add(item Noodle) error {
	if err := db.Handle.Add(item.Id, item); err != nil {
		log.Print(err)
		return err
	}
	return nil
}

func (db *Database) Update(item Noodle) error {
	if err := db.Handle.Add(item.Id, item); err != nil {
		log.Print(err)
		return err
	}
	return nil
}

func (db *Database) Delete(id string) error {
	if err := db.Handle.Delete(id); err != nil {
		log.Print(err)
		return err
	}
	return nil
}

func (db *Database) Close() error {
	return db.connection.Close()
}
