package monitor

import (
	"local/rssmon3/config"
	"os"
	"testing"
	"time"
)

func initItem() {
	os.Args = []string{"a", "-db", "map"}
	if err := config.New(); err != nil {
		panic(err)
	}
}

func TestItemNewItem(t *testing.T) {
	initItem()

	i, err := NewItem("NewItem", time.Second)
	if err != nil {
		t.Fatal(err)
	}
	if i.Key != "NewItem" {
		t.Fatal(i.Key)
	}
}

func TestItemCompare(t *testing.T) {
	initItem()

	i, _ := NewItem("iCompare", time.Second)
	j, _ := NewItem("jCompare", 10*time.Second)
	if c := i.Compare(j); c != 1 {
		t.Fatal(c)
	}

	i, _ = NewItem("iCompare", time.Second)
	j, _ = NewItem("iCompare", time.Second)
	if c := i.Compare(j); c != 0 {
		t.Fatal(c)
	}

	i, _ = NewItem("iCompare", 10*time.Second)
	j, _ = NewItem("jCompare", time.Second)
	if c := i.Compare(j); c != -1 {
		t.Fatal(c)
	}
}

func TestItemInterval(t *testing.T) {
	initItem()

	i, _ := NewItem("iInterval", 10*time.Second)
	if i := i.Interval(); i != 10*time.Second {
		t.Fatal(i)
	}
}

func TestItemGetSetInterval(t *testing.T) {
	initItem()

	i := &Item{Key: "GetSetInterval"}

	if i, err := i.getInterval(); err == nil {
		t.Errorf("get interval of unset passes")
	} else if i != forever {
		t.Errorf("failing get interval is not forever")
	}

	if err := i.setInterval(time.Minute); err != nil {
		t.Errorf("failing set interval: %v", err)
	}

	if i, err := i.getInterval(); err != nil {
		t.Errorf("get interval of set fails: %v", err)
	} else if i != time.Minute {
		t.Errorf("passing get interval is not time.Minute")
	}
}

func TestItemLastMark(t *testing.T) {
	initItem()

	i, _ := NewItem("iLastMark", 100*time.Millisecond)

	first := i.Last()
	if first.Sub(time.Now().Add(-100*time.Millisecond)) > time.Millisecond*200 {
		t.Errorf("default last is wrong: %v", first)
	}

	i.Mark()
	second := i.Last()
	if first == second {
		t.Errorf("mark() didn't change last")
	}
	if second.Sub(time.Now()) > time.Millisecond*100 {
		t.Errorf("marked last is wrong: %v", second)
	}
}

func TestItemGetSetLast(t *testing.T) {
	initItem()

	i := &Item{Key: "iGetSetLast"}

	if i, err := i.getLast(); err == nil {
		t.Errorf("get last of unset passes")
	} else if i != never {
		t.Errorf("failing get last is not never")
	}

	stamp := time.Now()
	if err := i.setLast(stamp); err != nil {
		t.Errorf("failing set last: %v", err)
	}

	if i, err := i.getLast(); err != nil {
		t.Errorf("get last of set fails: %v", err)
	} else if i.Sub(stamp) > time.Millisecond*10 {
		t.Errorf("passing get last is not %v: got %v (+%v)", stamp, i, i.Sub(stamp))
	}
}
