package public

import(
	"os"
	"os/exec"
	"github.com/lxn/walk"
	"strings"
	registry "github.com/golang/sys/windows/registry"
	"golang.org/x/text/encoding/simplifiedchinese"
)

//
//
// Get Env
// 

// 获取环境变量
func GetEnv(e string) string{
	return os.Getenv(e)
}
// 获取fqdn
func GetEnvFqdn(s string)string{
	cmd,err := exec.Command("whoami","/fqdn").Output()
	if err !=nil {
		PntError(err)
	}
	out,err := simplifiedchinese.GBK.NewDecoder().Bytes(cmd)
	if err !=nil {
		PntError(err)
	}

	for _,each := range strings.Split(string(out),","){
		if strings.Index(each,s) != -1{
			return  each[3:]
		}
	}
	return ""
}

//
//
//  local exec
//

func execcmd_base(cmdargs string) (string,[]string,error){
	if cmdargs == "" {
		return "",nil,Error_NullCommand
	}

	var app string
	var appargs []string

	spaceindex:=strings.Index(cmdargs," ")
	if spaceindex != -1{
		app 		= cmdargs[:spaceindex]
		appargs 	= strings.Split(cmdargs[spaceindex+1:]," ")
	}else{
		app 		= cmdargs
		appargs[0] 	= ""
	}
	PntInfo(app,appargs)

	return app,appargs,nil
}
func Execcmd_nowait(cmdargs  string){
	app,appargs,err :=execcmd_base(cmdargs)
	if err !=nil{
		PntError(err)
		return 
	}
	if err := exec.Command(app,appargs...).Start();err !=nil {
		PntError(err)
	}
}
func Execcmd_wait(cmdargs  string,){
	app,appargs,err :=execcmd_base(cmdargs)
	if err !=nil{
		PntError(err)
		return
	}
	cmd := exec.Command(app,appargs...)
	if err := cmd.Start(); err != nil {
		PntError(err)
	}
	err = cmd.Wait()
	if err !=nil{
		PntError("Command finished with error: ",err)
	}
}
func Execcmd_output(cmdargs  string)[]byte{
	app,appargs,err :=execcmd_base(cmdargs)
	if err !=nil{
		PntError(err)
		return nil
	}
	if out,err2 := exec.Command(app,appargs...).CombinedOutput();err2 !=nil {
		PntError(err2)
	}else{
		return out
	}
	return nil
}


//
//
//  local 
//

func ChooseFolder(explain, initDir * string) string {
	fg := new(walk.FileDialog)
	fg.Title = *explain
	fg.InitialDirPath = *initDir
	fg.ShowBrowseFolder(*new(walk.Form))
	return fg.FilePath
}
func OpenWindow(s string){
	Execcmd_nowait("explorer "+s)
}


//
//
//  remote exec
//

// 以管理员，立刻返回
func PsExec_sd(pc ,cmd string) {
	psExecCommand := `psexec \\` + pc + " -s -d "+cmd
	Execcmd_nowait(psExecCommand)
}
// 以管理员，立刻返回，指定会话，执行远程程序
func PsExec_sdi(pc ,cmd ,sessionid string) {
	psExecCommand := `psexec \\` + pc + " -s -d -i "+sessionid +" "+cmd 
	Execcmd_nowait(psExecCommand)
}
// 以管理员，立刻返回，指定会话，发送本地程序要远程主机，再执行
func PsExec_sdic(pc ,cmd ,sessionid string) {
	psExecCommand := `psexec \\` + pc + " -s -d -i "+sessionid + " -c "+cmd 
	Execcmd_nowait(psExecCommand)
}


//
//
//  msg show
//

// UI：显示带确定的消息框
func Msg(message  string)  {
	walk.MsgBox(*new(walk.Form), "提示", message, walk.MsgBoxIconInformation)	
}
// UI:显示带确定和取消的消息框
// 点击确定按钮：返回1，
// 点击取消按钮：返回2
func Msg_YesNo(message  string) int {
	return walk.MsgBox(*new(walk.Form), "提示", message, walk.MsgBoxOKCancel)	
}
// 调用外部命令的MsgBox
func MsgBox(message string){
	Execcmd_nowait("msg * /TIME:60 "+ message)
}
// 调用外部命令的指定计算机的消息的MsgBox
func SysMsgBox(pc,message string){
	Execcmd_nowait("msg * /SERVER:"+pc+" /TIME:60 "+ message)
}


//
//
//  regedit base
//

func reg_prase(root * int) registry.Key{
	switch *root{
	case HKCU:
		return registry.CURRENT_USER
	case HKU:
		return registry.USERS
	case HKLM:
		return registry.LOCAL_MACHINE
	}
	return registry.LOCAL_MACHINE
}
func Reg_Exist_item(root int,path string ) {
	//_,exist,err := 
	registry.CreateKey(reg_prase(&root),path,registry.ALL_ACCESS)
}
func Reg_query_item_one(root int ,path string) string {
	if k, kerr := registry.OpenKey(reg_prase(&root),path, registry.READ);kerr==nil{
		defer k.Close()
		if sk,err := k.ReadSubKeyNames(1); err ==nil{
			return sk[0]
		} else{
			return ""
		}
	} else {
		return ""
	}
}
func Reg_query_key_one(root  int, path, key string) string {
	if k, kerr := registry.OpenKey(reg_prase(&root),path, registry.READ);kerr==nil{
		defer k.Close()
		if sk,_,err := k.GetStringValue(key); err ==nil{
			return sk
		} else{
			return ""
		}
	} else {
		return ""
	}
}
func Reg_Write_key_one(root int, path, name, value string) {
	if k, kerr := registry.OpenKey(reg_prase(&root),path, registry.WRITE);kerr==nil{
		defer k.Close()
		k.SetStringValue(name, value)
	}
}


//
//
// reg func for domain computer
//

func Reg_Write_DC(key , value string){
	Reg_Write_key_one(
		Reg_Root_dc,
		Reg_Path_home,
		key,
		value)
}
func Reg_Query_DC(key string) string {
	return Reg_query_key_one(
		Reg_Root_dc,
		Reg_Path_home,
		key)
}


//
//
// reg func for AD
//

func Reg_Query_AC_DC(pc ,key string)string {
	return Reg_query_key_one(
		Reg_Root_ac,
		Reg_Path_home_ac + pc,
		key)
}


//
//
// File operate
//

// 存在文件
func Exist(path string) bool {
	_, err := os.Stat(path)    	// os.Stat获取文件信息

	return  !os.IsNotExist(err)
}
// 不存在文件
func NotExist(path string) bool {
	_, err := os.Stat(path)    //os.Stat获取文件信息
	return os.IsNotExist(err)
}
// 是否为文件夹
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)
}


//
//
// Folder operate
//

// 创建文件夹
func Mkdir(dir string){
	os.Mkdir(dir,os.ModeSetuid)
}
// 读取文件夹目录
func ReadDir(s string) ([]os.FileInfo,error){
	f,err := ioutil.ReadDir(s)
	return f,err
}
// 获取最新修改的文件夹
func GetNewFolder(rdir ,extdir string) string {
	f,err := ioutil.ReadDir(rdir)
	if err !=nil{
		PntError(err)

	}
	firstModTime	:= f[0].ModTime()
	firstName		:= f[0].Name()
	for _,i  := range f{
		fileModTime := i.ModTime()
		filename 	:= i.Name()
		if i.IsDir() && i.Name() != extdir{
			if firstModTime.Before(fileModTime){
				firstModTime 	= fileModTime
				firstName		= filename
			}

		}
	}
	return firstName
}