package models

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os/exec"
	"strconv"
	"time"
)

type NetworkTime struct {
	Ntime string
	Ndate string
}

// 结构体两个参数是Ntime 第二个参数是Ndate
func (class *NetworkTime) Init() *NetworkTime {
	url := "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp"
	myhttp := &http.Client{}
	myhttp.Timeout = time.Duration(3 * time.Second)
	resp, err1 := myhttp.Get(url)
	if err1 != nil {
		return nil
	}
	defer resp.Body.Close()
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		return nil
	}
	m := make(map[string]interface{})
	json.Unmarshal(body, &m)
	mm := m["data"].(map[string]interface{})
	str := mm["t"].(string)
	result := str[0:10]
	class.Ntime = result
	reI, _ := strconv.ParseInt(result, 10, 64)
	tm := time.Unix(reI, 0)
	class.Ndate = tm.Format("2006-01-02 15:04:05")
	return class
}

// linux 校准时间
func (class *NetworkTime) Calibration() bool {
	if class == nil {
		return false
	}
	err := exec.Command("date", "-s", class.Ndate).Run()
	if err != nil {
		return false
	} else {
		return true
	}
}
