// Copyright (C) 2019 Marius Schellenberger

package db

import (
	"git.giftfish.de/ston1th/docstore/pkg/core"
	"git.giftfish.de/ston1th/docstore/pkg/index"
	"git.giftfish.de/ston1th/docstore/pkg/store"
	"io"
	"path/filepath"
)

const (
	storeFile  = "store.db"
	bcryptCost = 13
)

const blevePath = "bleve"

type DB struct {
	store store.Store
	Index *index.Index
}

func New(cfg core.Config) (db *DB, err error) {
	db = new(DB)
	dbFile := filepath.Join(cfg.RunDir, storeFile)
	db.store, err = store.NewBoltStore(dbFile, nil)
	if err != nil {
		return
	}
	db.Index, err = index.NewIndex(filepath.Join(cfg.RunDir, blevePath))
	if err != nil {
		return
	}
	err = db.UnlockUser()
	if err != nil && err != store.ErrKeyNotFound {
		return
	}
	err = db.RunMigrations()
	return
}

func (db *DB) Dump(w io.Writer) error {
	return db.store.Dump(w)
}

func (db *DB) Restore(r io.Reader) error {
	return db.store.Restore(r)
}

func (db *DB) Close() (err error) {
	err = db.store.Close()
	if err != nil {
		return
	}
	return db.Index.Close()
}
