package main

import (
	"log"
	"testing"
	"time"
)

func TestSession(t *testing.T) {
	id := "testopenid"
	procedure := "test procedure"

	s := openIDSessionData{}
	s.OpenID = id
	s.Procedure = procedure

	//delete any existing
	s.Delete()
	path := getSessionPath(id)
	AssertEqual(t, isFileExist(path), false, "Session file should not exist")

	//create new
	original := createEmptySession(id, 100)
	original.Procedure = procedure
	original.Save()

	//wait 1 sec
	log.Print("wait for 1 sec for testing timestamp ......")
	time.Sleep(1 * time.Second)
	log.Print("......waiting done")

	//read back , check state
	s.Load(id)
	AssertEqual(t, s.OpenID, id, "")
	AssertEqual(t, s.Procedure, procedure, "")
	now := int32(time.Now().Unix())

	//check timing
	AssertEqual(t, s.Expire > now, true, "Expire should be in future")
	AssertEqual(t, s.UpdateAt < now, true, "Update should be in pass")
	AssertEqual(t, s.CreateAt == s.UpdateAt, true, "Update should be equal to create")
	AssertEqual(t, isExpired(now), false, "current time should not be expired")

	//update existing session
	s.setKvPair("key", "value")
	s.setKvPair("key1", "value1")
	//timeing should be exactly 1s diff
	AssertEqual(t, s.CreateAt+1 == s.UpdateAt, true, "second Update should be bigger create")

	s.Save()
	n := openIDSessionData{}
	n.Load(id)
	AssertEqual(t, n.KvPair["key"], "value", "key = value ")
	AssertEqual(t, n.KvPair["key1"], "value1", "key1 = value1")

	//delete session, for clean up
	n.Delete()
	path = getSessionPath(id)
	AssertEqual(t, isFileExist(path), false, "Session file should not exist")
}
