package main

// #cgo LDFLAGS: -lstatgrab
// #include <statgrab.h>
import "C"
import "time"

var mainfunc = make(chan func())

func do(f func()) {
	done := make(chan bool, 1)
	mainfunc <- func() {
		f()
		done <- true
	}
	<-done
}

func (s *Stat) CPUStats() *CPUStats {
	s.Lock()
	defer s.Unlock()

	var cpu *CPUStats

	do(func() {
		cpup := C.sg_get_cpu_percents_of(C.sg_new_diff_cpu_percent, nil)
		loadStat := C.sg_get_load_stats(nil)
		cpu = &CPUStats{
			User:      float64(cpup.user),
			Kernel:    float64(cpup.kernel),
			Idle:      float64(cpup.idle),
			IOWait:    float64(cpup.iowait),
			Swap:      float64(cpup.swap),
			Nice:      float64(cpup.nice),
			LoadMin1:  float64(loadStat.min1),
			LoadMin5:  float64(loadStat.min5),
			LoadMin15: float64(loadStat.min15),
			Period:    time.Duration(int(cpup.time_taken)) * time.Second,
			TimeTaken: time.Now(),
		}
	})
	return cpu
}
