package utility

import (
	"encoding/json"
	"gadmin/config"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"math/rand"
	"os"
	"sync"
	"time"
)

func SaveDb(lock *sync.Mutex, val interface{}, fileName string) (err error) {
	lock.Lock()
	defer lock.Unlock()

	content, _ := json.Marshal(val)

	// 本地运行时，避免权限问题直接写入库
	if config.SysType == "windows" {
		if err = ioutil.WriteFile(fileName, content, 0666); err != nil {
			logrus.Panic("cannot windows SaveDb, err:" + err.Error())
		}
		return nil
	}

	tmpName := RandString(16)
	err = ioutil.WriteFile(tmpName, content, 0666) //写入文件(字节数组)
	if err != nil {
		os.Remove(tmpName)
		logrus.Panic("cannot SaveToBak, err:" + err.Error())
	} else {
		if exist, _ := PathExists(fileName); exist {
			if err := os.Remove(fileName); err != nil {
				logrus.Panic("cannot remove, err:" + err.Error())
			}
		}

		if err = os.Rename(tmpName, fileName); err != nil {
			logrus.Panic("cannot SaveToBak, err:" + err.Error())
		}

	}

	return
}

func LoadDb(lock *sync.Mutex, fileName string, val interface{}) (err error) {
	file, err := os.OpenFile(fileName, os.O_RDONLY, 0666)
	if err != nil {
		return
	}
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return
	}

	err = json.Unmarshal(content, val)
	return
}

func RandString(len int) string {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	bytes := make([]byte, len)
	for i := 0; i < len; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}
