// Copyright (C) 2019 Marius Schellenberger

package db

import (
	"git.giftfish.de/ston1th/docstore/pkg/core"
)

const (
	idPrefix   = "id/"
	pathPrefix = "path/"
)

func (db *DB) GetPaths(res []core.Result) error {
	for i, v := range res {
		err := db.store.Get(pathPrefix+v.ID, &res[i].Path)
		if err != nil {
			return err
		}
	}
	return nil
}

func (db *DB) GetIndexed(p core.Paths) {
	for i, v := range p {
		p[i].Flag = db.IsIndexed(v.Abs)
	}
}

func (db *DB) IsIndexed(path string) bool {
	return db.store.Get(idPrefix+path, nil) == nil
}

func (db *DB) GetPath(id string) (path string, err error) {
	err = db.store.Get(pathPrefix+id, &path)
	return
}

func (db *DB) GetID(path string) (id string, err error) {
	err = db.store.Get(idPrefix+path, &id)
	return
}

func (db *DB) DeletePath(id string) error {
	return db.store.Delete(pathPrefix + id)
}

func (db *DB) DeleteID(path string) error {
	return db.store.Delete(idPrefix + path)
}

func (db *DB) NewFile(id, path string) (err error) {
	err = db.store.Set(idPrefix+path, id)
	if err != nil {
		return
	}
	err = db.store.Set(pathPrefix+id, path)
	return
}

func (db *DB) MoveFile(op, np string) error {
	if !db.IsIndexed(op) {
		return nil
	}
	id, err := db.DeleteFile(op)
	if err != nil {
		return err
	}
	return db.NewFile(id, np)
}

func (db *DB) DeleteFile(path string) (id string, err error) {
	if !db.IsIndexed(path) {
		return
	}
	id, err = db.GetID(path)
	if err != nil {
		return
	}
	err = db.DeleteID(path)
	if err != nil {
		return
	}
	err = db.DeletePath(id)
	return
}
