package gupta

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"
)

func TestFreeMem(t *testing.T) {
	m := Memory{}
	m.Free = uint64(1200)
	got := m.Free
	want := uint64(1200)
	name := "free"
	if got != want {
		t.Errorf("got %s %d want %d", name, got, want)
	}
}

func TestTotalMem(t *testing.T) {
	m := Memory{Total: uint64(2400)}
	got := m.Total
	want := uint64(2400)
	name := "total"
	if got != want {
		t.Errorf("got %s %d want %d", name, got, want)
	}
}

func TestUsedMem(t *testing.T) {
	m := Memory{Total: uint64(2400), Free: uint64(1200)}
	got := m.Used()
	want := uint64(1200)
	name := "used"
	if got != want {
		t.Errorf("got %s %d want %d", name, got, want)
	}
}

func TestNewMemory(t *testing.T) {
	//r, _ := os.open("/proc/meminfo")
	r := strings.NewReader("MemTotal:       16080192 kB\nMemFree:         3617004 kB\nMemAvailable:   11258504 kB\nBuffers:         1814108 kB\n")
	mem := NewMemory(r)
	t.Run("Test that we can get total memory", func(t *testing.T) {
		got := mem.Total
		want := uint64(16080192)
		name := "memory total"
		if got != want {
			t.Errorf("got %s %d want %d", name, got, want)
		}
	})

	t.Run("Test that we can properly report Memory usage", func(t *testing.T) {
		var buff bytes.Buffer
		enc := json.NewEncoder(&buff)
		enc.Encode(&mem)
		report := buff.String()
		reportFields := strings.Split(report, ":")
		if reportFields[2] != "\"16080192KB\",\"used\"" {
			t.Errorf("Encoding report failed")
		}
	})
}