package public
import (
	"os"
	"encoding/json"
	"bytes"
	"strings"
	"net"
	"bufio"
	"math/rand"
	"time"
	"os/exec"
	"io/ioutil"
	"strconv"
	
	"golang.org/x/text/encoding/simplifiedchinese"
)
// 获取 环境变量
// 如果空 输出错误
// 但不退出
func GetEnv(e string) string{
	r := os.Getenv(e)
	DebugLog(e,"->",r)
	// 获取为空
	if r == "" {
		PrintLog("环境错误！")
	}
	return r
}
func GetEnvFqdn(s string)string{
	cmd,err := exec.Command("whoami","/fqdn").Output()
	if err !=nil {
		PrintLog(err)
	}
	out,err := simplifiedchinese.GBK.NewDecoder().Bytes(cmd)
	if err !=nil {
		PrintLog(err)
	}

	for _,each := range strings.Split(string(out),","){
		if strings.Index(each,s) != -1{
			return  each[3:]
		}
	}
	return ""
}
// 获取 消息内容
func ParseJsonHead(b []byte)string{
	//{"msgtype":"report","msgstate":"","username":"zhiweiadserver","computername":"ADSERVER","report":"下班"}
	// 提取第一个冒号后的第二位和第一个逗号的前一位
	// 也就是msgtype的内容
	msgtype := b[bytes.IndexByte(b,':')+2:bytes.IndexByte(b,',')-1]

	return string(msgtype)
}

// 解析Json 并放到变量中
func ParseJsonBody(unmsg []byte,v interface{}){
	// 填写
	if err := json.Unmarshal(unmsg,v) ;err != nil{
		PrintLog("Parse Json Error ",err)
	}
}

// Jsom 转 Byte
func JsonToByte(v interface{}) []byte{
	textbyte,err := json.Marshal(v)
	if err !=nil {
		PrintLog("Json to String Error ",v,err)
	}
	return textbyte
}

// 是否存在
func Exists(path string) bool {
	_, err := os.Stat(path)    //os.Stat获取文件信息
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}
// 是否为文件夹
func IsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

// 是否为文件
func IsFile(path string) bool {
	return !IsDir(path)
}

func Mkdir(dir string){
	os.Mkdir(dir,os.ModeSetuid)
}
func WriteBytesFile(file string ,data []byte)error{
	return ioutil.WriteFile(file,data,os.ModeSetuid)
}
func CreateExtTempate(dist*string) []byte {
	base := BackupReplaceKey
	var ret bytes.Buffer
	file, err := os.Open(DocuBase + BackupVersion + "base"+BackupExtFile)
    if err != nil {
		PrintLog(err)
		return nil
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
		lineText := scanner.Bytes()
		if bytes.Index(lineText,base) != -1 {
			lineText = bytes.Replace(lineText,base, []byte(*dist),1)
		}
		ret.Write(lineText)
		ret.Write([]byte("\n"))
	}
	//PrintLog(ret.String())
	return ret.Bytes()
}

// 从连接中 获取ip
func GetConnIP(s net.Addr) string {
	return strings.Split(s.String(),":")[0]
}
func IfPrimaryUser(s string) bool{
	if strings.Index(s,"zhiwei") == -1{
		return true
	}
	return false
}
func Rand(i int)string{
	rand.Seed(time.Now().UnixNano())
	return strconv.Itoa(rand.Intn(i))
}
func Delay(s * string){
	DebugLog("延迟",*s,"秒")
	i,_ := strconv.Atoi(*s)
	time.Sleep(time.Duration(i) * time.Second)
}
func TheUser(s * string)bool{
	if *s == Env_fqdn_cn || *s == "taotengfei" || *s == "tengfei" || *s == "zhiweiadserver" {return true}
	return false
}