package ledger

import "testing"

func TestBalances(t *testing.T) {
	t.Run("push", func(t *testing.T) {
		b := make(Balances)
		b.Push(Delta{Name: "x", Currency: "y", Value: 0.1})
		b.Push(Delta{Name: "x", Currency: "y", Value: 1.2})
		b.Push(Delta{Name: "x", Currency: "z", Value: 2.3})
		ba := b["x"]
		if ba["y"] != 1.3 {
			t.Error(ba["y"])
		}
		if ba["z"] != 2.3 {
			t.Error(ba["z"])
		}
	})

	t.Run("pushall", func(t *testing.T) {
		a := make(Balances)
		a.Push(Delta{Name: "a", Currency: USD, Value: 0.1})
		a.Push(Delta{Name: "ab", Currency: USD, Value: 1.2})

		b := make(Balances)
		b.Push(Delta{Name: "b", Currency: USD, Value: 2.3})
		b.Push(Delta{Name: "ab", Currency: USD, Value: 3.4})

		b.PushAll(a)

		if len(a) != 2 {
			t.Error("modified original", len(a), a)
		}
		if a["a"][USD] != 0.1 {
			t.Error("modified original a", a["a"])
		}
		if a["ab"][USD] != 1.2 {
			t.Error("modified original ab", a["ab"])
		}

		if len(b) != 3 {
			t.Error("didnt union names", len(b), b)
		}
		if b["a"][USD] != 0.1 {
			t.Error("didnt pull other unique", b["a"])
		}
		if b["b"][USD] != 2.3 {
			t.Error("didnt retain unique", b["b"])
		}
		if b["ab"][USD] != 4.6 {
			t.Error("didnt sum other", b["ab"])
		}
	})

	t.Run("like", func(t *testing.T) {
		was := make(Balances)
		was.Push(Delta{Name: "a", Currency: USD, Value: 0.1})
		was.Push(Delta{Name: "ab", Currency: USD, Value: 1.2})

		got := was.Like(`^ab$`)
		if len(got) != 1 || got["ab"][USD] != 1.2 {
			t.Error(got)
		}

		got = was.NotLike(`^ab$`)
		if len(got) != 1 || got["a"][USD] != 0.1 {
			t.Error(got)
		}
	})

	t.Run("group", func(t *testing.T) {
		was := make(Balances)
		was.Push(Delta{Name: "a:1", Currency: USD, Value: 0.1})
		was.Push(Delta{Name: "a:2", Currency: USD, Value: 1.2})
		was.Push(Delta{Name: "b:1", Currency: USD, Value: 2.2})

		got := was.Group(`^[^:]*`)
		if len(got) != 2 {
			t.Error(got)
		}
		if got["a"][USD] != 1.3 {
			t.Error(got)
		}
		if got["b"][USD] != 2.2 {
			t.Error(got)
		}
	})
}
