package client

import (
	"log"
	"strconv"
	"time"

	"github.com/inhies/go-bytesize"
	"github.com/mackerelio/go-osstat/memory"
	"github.com/shirou/gopsutil/cpu"
)

// Look into using a ticker instead of a for-loop
func (client *Client) statusUpdater() {
	for {
		// Fetch CPU usage in percentages
		cpustats, err := cpu.Percent(time.Second, false)
		if err != nil {
			log.Println("ERROR: fetching CPU usage infor - ", err)
		}

		// Fetch memory stats in bytes
		mem, err := memory.Get()
		if err != nil {
			log.Println("ERROR: fetching memory info - ", err)
		}

		// Use the ByteSize package to allow for memory calculations
		b := bytesize.New(float64(mem.Used))

		// Prepare the message.
		update := "update;" + strconv.Itoa(int(cpustats[0])) + ";" + b.String() + ";" + strconv.Itoa(client.taskId)

		// Write the message to the server
		client.writeToServer(update)

	}
}
