package data

import (
	"encoding/json"
	"os"
	"path/filepath"
	"sync"

	"src.rybka.ca/pkg/types"
)

var (
	dataFile  = ""
	database  = &types.Database{}
	listeners = make(map[string]map[int64]chan string)
	mutexes   = make(map[string]*sync.Mutex)
	saveChan  = make(chan struct{})
)

func init() {
	// Read config
	dataFile = os.Getenv("DATA_FILE")
	if dataFile == "" {
		panic("DATA_FILE not set")
	}

	// Load data
	f, _ := os.Open(dataFile)
	json.NewDecoder(f).Decode(database)

	// Start storage writer
	go func() {
		for range saveChan {
			err := os.MkdirAll(filepath.Dir(dataFile), os.ModePerm)
			if err != nil {
				panic(err)
			}
			f, err := os.Create(dataFile)
			if err != nil {
				panic(err)
			}
			err = json.NewEncoder(f).Encode(database)
			if err != nil {
				panic(err)
			}
			err = f.Close()
			if err != nil {
				panic(err)
			}
		}
	}()
}

func Read(path string) string

func HasChange(path string, since int64) bool {
	return database.ModTimes[path] > since
}

func Write(path string, value string)

func Delete(path string)

func Listen(path string) (chan string, int64)

func Unlisten(path string, id int64)
