package main

import (
	"encoding/json"
	"fmt"
	"log"

	scribble "github.com/nanobox-io/golang-scribble"
)

type DB struct {
	Db *scribble.Driver
}

func InitDb(dbPath string) *DB {
	var err error
	var db = &DB{}

	if dbPath == "" {
		dbPath = "DB"
	}

	db.Db, err = scribble.New(dbPath, nil)
	if err != nil {
		fmt.Println("Error", err)
	}

	log.Printf("App: %+v", db)

	return db
}

func (db *DB) Write(table string, key string, value interface{}) error {
	err := db.Db.Write(table, key, value)
	if err != nil {
		fmt.Println("Error", err)
		return err
	}
	return nil
}

func (db *DB) Read(table string, key string, value interface{}) error {
	err := db.Db.Read(table, key, value)
	if err != nil {
		fmt.Println("Error", err)
		return err
	}
	return nil
}

func (db *DB) loadHeats() []Heat {
	records, err := db.Db.ReadAll("Heat")
	if err != nil {
		fmt.Printf("read error: %+v", err)
	}

	heats := make([]Heat, 0)
	for _, record := range records {
		var heat Heat
		err = json.Unmarshal([]byte(record), &heat)
		if err != nil {
			fmt.Printf("decode error: %+v", err)
		}
		heats = append(heats, heat)
	}

	return heats
}

func (db *DB) loadSurfers() []Athlete {
	records, err := db.Db.ReadAll("Surfers")
	if err != nil {
		fmt.Printf("read error: %+v", err)
	}

	athletes := make([]Athlete, 0)
	for _, record := range records {
		var athlete Athlete
		err = json.Unmarshal([]byte(record), &athlete)
		if err != nil {
			fmt.Printf("decode error: %+v", err)
		}
		athletes = append(athletes, athlete)
	}

	return athletes
}
