package pai_service

import (
	"os/exec"
	"fmt"
	"io"
	"strings"
	"bufio"
	"chain33-pai/pkg/chain33"
	"chain33-pai/pkg/logging"
	"github.com/33cn/chain33/types"
)

var (
	pai_serial string
)

type Pai struct {
	Hardware string `json:"hardware"`
	Revision string	`json:"revision"`
	Serial   string `json:"serial"`
	//PeerList *types.PeerList
	LocalLastHeight int64 `json:"local_last_height"`
	LastHeight int64 `json:"last_height"`
	IsNtpSync  bool	`json:"is_ntp_sync"`
	WalletStatus *types.WalletStatus `json:"wallet_status"`
	NetInfo *types.NodeNetInfo `json:"net_info"`
}

func (p *Pai) GetConfig() bool {
	if pai_serial != "" {
		p.Serial = pai_serial
	}
	if p.Serial != "" {
		return true
	}
	config ,err := getPaiConfig("cat","/proc/cpuinfo")
	if err != nil {
		return false
	}
	if _,ok := config["serial"];ok {
		p.Serial = config["serial"]
		p.Hardware = config["hardware"]
		p.Revision = config["revision"]
		return true
	}
	return false
}

func (p *Pai) GetDevstatus() error {
	client := &chain33.PaiClient{}
	peerinfo,err := client.GetPeerInfo()
	if err != nil {
		logging.Error("GetDevstatus peerinfo err",err)
		return err
	}

	for _,v := range peerinfo.Peers {
		if p.LastHeight < v.Header.Height {
			p.LastHeight = v.Header.Height
		}
		if v.Self {
			p.LocalLastHeight = v.Header.Height
		}
	}
	sync ,err := client.IsNtpClockSync()
	if err != nil {
		logging.Error("GetDevstatus IsNtpClockSync err",err)
		return err
	}
	p.IsNtpSync = sync.IsOk
	netinfo,err := client.GetNetInfo()
	if err != nil {
		logging.Error("GetDevstatus GetNetInfo err",err)
		return err
	}
	p.NetInfo = netinfo
	walletstatus,err := client.GetWalletStatus()
	if err != nil {
		logging.Error("GetDevstatus GetWalletStatus err",err)
		return err
	}
	p.WalletStatus = walletstatus
	return nil
}

func getPaiConfig(command string ,arg ...string) (config map[string]string,err error) {
	//获取操作系统版本信息

	list := make(map[string]string, 0)
	cmd := exec.Command("cat", arg...)
	stdout, err := cmd.StdoutPipe()
	//fmt.Println(stdout)
	if err != nil {
		fmt.Println(err)
		return nil,err
	}
	defer stdout.Close()
	if err := cmd.Start(); err != nil {
		fmt.Println(err)
		return nil,err
	}
	rd := bufio.NewReader(stdout)
	for {
		line, err := rd.ReadString('\n')
		if err!=nil || io.EOF==err{
			break
		}else{
			//fmt.Println("line", line)
			l := strings.Split(line, ":")

			if len(l) == 2 {
				k := strings.ToLower(strings.TrimRight(strings.Trim(strings.Replace(l[0], "	", " ", -1), " "), " "))
				v := strings.Trim(strings.Replace(l[1], "\n", "", -1), " ")
				//fmt.Println("KEY:",k, "VAL:", v)
				if _, ok := list[k]; !ok {
					list[k] = v
					if k == "serial" {
						pai_serial = v
					}
				}
			}
		}
	}

	return list, nil
}