package ping

import (
	"netease_control_center/interfaces/log"
	"os/exec"
	"strconv"
	"time"
)

func RunPing(sec uint32, address string) error {
	if data, err := exec.Command("ping", "-w", strconv.Itoa(int(sec)), address).CombinedOutput(); err == nil {
		log.Println(log.DebugLog, "Ping ", address, " result:", string(data))
		return nil
	} else {
		log.Println(log.DebugLog, "Ping ", address, " error!", err, string(data))
		return err
	}
}

func JustPing(sec uint32, address string) error {
	return exec.Command("ping", "-w", strconv.Itoa(int(sec)), address).Run()
}

func RunCmd(cmd string) {
	if data, err := exec.Command(cmd).CombinedOutput(); err == nil {
		log.Println(log.DebugLog, "Cmd ", cmd, " result:", string(data))
	} else {
		log.Println(log.DebugLog, "Cmd ", cmd, " error!", err, string(data))
	}
}

func RunCmdArg(cmd string, arg ...string) {
	if data, err := exec.Command(cmd, arg...).CombinedOutput(); err == nil {
		log.Println(log.DebugLog, "Cmd ", cmd, " result:", string(data))
	} else {
		log.Println(log.DebugLog, "Cmd ", cmd, " error!", err, string(data))
	}
}

func Outerpingtest() {
	pinger, err := NewPinger("www.baidu.com")
	if err != nil {
		panic(err)
	}
	pinger.SetPrivileged(true)
	pinger.Count = 3
	pinger.Run()                 // blocks until finished
	stats := pinger.Statistics() // get send/receive/rtt stats
	log.Printf(log.DebugLog, "Get: %+v\n", stats)
}

func GolangPing(count int, server string) (*Statistics, error) {
	pinger, err := NewPinger(server)
	if err != nil {
		return nil, err
	}

	pinger.SetPrivileged(true)
	pinger.Count = count
	pinger.Timeout = 5 * time.Second
	pinger.Run() // blocks until finished

	return pinger.Statistics(), nil // get send/receive/rtt stats
}

func GolangPingTimeout(costtime time.Duration, server string, recvPack int) (*Statistics, error) {
	pinger, err := NewPinger(server)
	if err != nil {
		return nil, err
	}

	pinger.SetPrivileged(true)
	pinger.Count = recvPack
	pinger.Timeout = costtime
	pinger.Interval = 1000 * time.Millisecond
	pinger.OnRecv = func(pkt *Packet) {
		//fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
		//	pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
	}
	pinger.Run() // blocks until finished

	return pinger.Statistics(), nil // get send/receive/rtt stats
}
