package nmslib

import (
	"errors"
	"io/ioutil"
	"os"
)

/*NmsTemp - Global string variable
Location of instance temporary directory
Dir Structure:
	- NmsTemp
		-
*/
var NmsTemp string

/*Initialize temporary directory
create a temp dir and save location to `NmsTemp` string
*/
func init() {
	// create temp dir
	temploc, err := ioutil.TempDir("", "nmslib-")
	if err != nil {
		panic(err)
	}
	NmsTemp = temploc

	//Create directory structure
	err = os.Mkdir(NmsTemp+"/assets", 0755)
	if err != nil {
		panic(errors.New("failed to create temporary folder"))
	}
	err = os.Mkdir(NmsTemp+"/assets/lang", 0755)
	if err != nil {
		panic(errors.New("failed to create temporary folder"))
	}
	err = os.Mkdir(NmsTemp+"/assets/glyphs", 0755)
	if err != nil {
		panic(errors.New("failed to create temporary folder"))
	}
	err = os.Mkdir(NmsTemp+"/assets/glyphs/dark", 0755)
	if err != nil {
		panic(errors.New("failed to create temporary folder"))
	}
	err = os.Mkdir(NmsTemp+"/assets/glyphs/light", 0755)
	if err != nil {
		panic(errors.New("failed to create temporary folder"))
	}

	//Write language files to temp directory
	fileloc := [4]string{"atlas-lang.csv", "gek-lang.csv", "korvax-lang.csv", "vykeen-lang.csv"}
	for x := 0; x < 4; x++ {
		data, err := Asset("assets/lang/" + fileloc[x])
		if err != nil {
			panic(errors.New("can not load: " + fileloc[x]))
		}
		err = ioutil.WriteFile(NmsTemp+"/assets/lang/"+fileloc[x], []byte(data), 0644)
		if err != nil {
			panic(errors.New("can not write " + fileloc[x] + " to temp dir"))
		}

	}
}

/*CleanUp removes temporary directory an it's contents
this is intended to be called in a defer statement in func main
takes no input
*/
func CleanUp() {
	os.RemoveAll(NmsTemp)
}
