package rawdb

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
)

type RawDb struct {
	path string
}

func NewRawDb(root string, dir string) *RawDb {
	full := filepath.Join(root, dir)
	if !dirExists(full) {
		if err := os.Mkdir(full, 0755); err != nil {
			panic(fmt.Sprintf("create rawdb failed:%s:%s", full, err.Error()))
		}
	}

	return &RawDb{path: full}
}

func (r *RawDb) Get(key []byte) ([]byte, error) {
	d := filepath.Join(r.path, string(key))
	return ioutil.ReadFile(d)
}

func (r *RawDb) Set(key []byte, value []byte) error {
	d := filepath.Join(r.path, string(key))
	return ioutil.WriteFile(d, value, 0644)
}

func dirExists(path string) bool {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false
	}
	return true
}
