// +build windows

package staros

import (
	"errors"
	"fmt"
	"os/exec"
	"strconv"

	"b612.me/wincmd"
)

// FindProcessByName 通过进程名来查询应用信息
func FindProcessByName(pname string) (data []Process, err error) {
	var lists []map[string]string
	lists, err = wincmd.GetRunningProcess()
	if err != nil {
		return
	}
	for _, v := range lists {
		if v["name"] == pname {
			var tmp Process
			tmp.Name = pname
			tmp.Pid, _ = strconv.ParseInt(v["pid"], 10, 64)
			tmp.PPid, _ = strconv.ParseInt(v["ppid"], 10, 64)
			data = append(data, tmp)
		}
	}
	return
}

// FindProcessByPid 通过pid来查询应用信息
func FindProcessByPid(pid int64) (data Process, err error) {
	var lists []map[string]string
	lists, err = wincmd.GetRunningProcess()
	if err != nil {
		return
	}
	for _, v := range lists {
		if v["pid"] == fmt.Sprint(pid) {
			data.Name = v["name"]
			data.Pid = pid
			data.PPid, _ = strconv.ParseInt(v["ppid"], 10, 64)
			return
		}
	}
	err = errors.New("Not Found")
	return
}

func Daemon(path string, args ...string) (int, error) {
	cmd := exec.Command(path, args...)
	if err := cmd.Start(); err != nil {
		return -1, err
	}
	pid := cmd.Process.Pid
	cmd.Process.Release()
	return pid, nil
}

func (starcli *StarCmd) SetRunUser(uid, gid uint32, groups []uint32) {

}

func (starcli *StarCmd) Release() error {
	if err := starcli.CMD.Start(); err != nil {
		return err
	}
	starcli.CMD.Process.Release()
	return nil
}
