package ntp

import (
	"os/exec"
	"time"
)

func SetUnixTimeToLocal(msec int64, diff time.Duration, trigCb bool) {
	sec := msec / 1000
	nsec := msec % 1000 * 1e6

	inTime := time.Unix(sec, nsec)
	SetTimeToLocalWithDiff(inTime, diff, trigCb)
}

func SetTimeToLocalWithDiff(toset time.Time, difftime time.Duration, trigCb bool) {
	//check toset if right, 1508137123 ---
	if toset.Before(time.Unix(1528697917, 0)) {
		return
	}
	localtime := time.Now().Local()
	currentdiff := localtime.Sub(toset)
	if currentdiff > difftime || currentdiff < -difftime {
		SetTimeToLocal(toset)
		if trigCb == true && CalTimeSuccessCb != nil {
			go CalTimeSuccessCb()
		}
	}
}

func SetTimeToLocal(toset time.Time) {
	cmd := exec.Command("date", "-s", toset.Format("2006.01.02-15:04:05"))
	cmd.Run()
}
