// Copyright (C) 2019 Marius Schellenberger

package db

import (
	"git.giftfish.de/ston1th/godrop/v2"
	"git.giftfish.de/ston1th/gowiki/pkg/cache"
	"git.giftfish.de/ston1th/gowiki/pkg/core"
	"git.giftfish.de/ston1th/gowiki/pkg/index"
	"git.giftfish.de/ston1th/gowiki/pkg/render"
	"git.giftfish.de/ston1th/gowiki/pkg/store"
	"io"
	"os"
	"path/filepath"
)

const (
	defUser     = "admin"
	defPassword = "gowiki"
	storeFile   = "store.db"
	bcryptCost  = 13
	welcome     = `# Welcome to GoWiki
This is the [Index](/wiki/Index) page.  
You can customize it how you like.`
)

const blevePath = "bleve"

type DB struct {
	admin     bool
	store     store.Store
	cache     *cache.Cache
	Index     *index.Index
	indexPath string
}

func New(cfg core.Config) (db *DB, err error) {
	db = &DB{admin: cfg.Admin, cache: cache.NewCache()}
	dbFile := filepath.Join(cfg.DataDir, storeFile)
	err = godrop.Unveil(dbFile, "rwc")
	if err != nil {
		return
	}
	db.store, err = store.NewBoltStore(dbFile, nil)
	if err != nil {
		return
	}
	db.indexPath = filepath.Join(cfg.DataDir, blevePath)
	db.Index, err = index.New(db.indexPath)
	if err != nil {
		return
	}
	if db.UserExists(defUser) != nil {
		err = db.CreateUser(defUser, defPassword, true)
		if err != nil {
			return
		}
	}
	err = db.UnlockUser(defUser)
	if err != nil {
		return
	}
	if db.SectionExists(core.WikiSection) != nil {
		err = db.CreateSection(core.WikiSection, []string{defUser}, false)
		if err != nil {
			return
		}
	}

	_, err = db.CreatePage(core.IndexPage, core.WikiSection, welcome, defUser, core.Public)
	if err != errPageExists && err != nil {
		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) (err error) {
	err = db.Index.Close()
	if err != nil {
		return
	}
	err = os.RemoveAll(db.indexPath)
	if err != nil {
		return
	}
	db.Index, err = index.New(db.indexPath)
	if err != nil {
		return
	}
	err = db.store.Restore(r)
	if err != nil {
		return
	}
	err = db.store.ForEachPrefix(pagePrefix, func(k string, _ []byte) error {
		p := new(core.Page)
		db.store.Get(pagePrefix+k, p)
		db.Index.Add(p.Title, p.StoreTitle, render.Render(p))
		return nil
	})
	return
}

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