package ntp

import (
	"errors"
	"fmt"
	"netease_control_center/interfaces/log"
	"time"
)

var (
	CalTimeSuccessCb func()

	NtpServers = []string{
		"ntp1.aliyun.com",
		"ntp2.aliyun.com",
		"ntp.sjtu.edu.cn",
		"0.cn.pool.ntp.org",
		"0.pool.ntp.org",
		"3.pool.ntp.org",
		"2.pool.ntp.org",
		"1.pool.ntp.org",
	}
)

func TestNtpServer() string {
	var tmp string
	for _, v := range NtpServers {
		t, e := Time(v)
		tmp += fmt.Sprintf("Server:%s, time:%+v, err:%+v\n", v, t, e)
	}

	return tmp
}

func CalTime(server string) error {
	if t, e := Time(server); e != nil {
		return e
	} else {
		SetTimeToLocalWithDiff(t, 2*time.Second, false)
		if CalTimeSuccessCb != nil {
			go CalTimeSuccessCb()
		}
		return nil
	}
}

func CalTimeWithDefaultServers() (server string, err error) {
	for _, v := range NtpServers {
		if err = CalTime(v); err == nil {
			return v, nil
		}
	}

	return "", errors.New("can not cal time")
}

func CalTimeUntilSuccess() {
	for {
		t := time.Now()
		if s, err := CalTimeWithDefaultServers(); err == nil {
			log.Println(log.DebugLog, "Cal time success! server: ", s, " coast time:", time.Now().Sub(t))
			break
		} else {
			time.Sleep(time.Second)
		}
	}
}
