package hotime

//session对象
type SessionIns struct {
	ShortCache CacheIns
	LongCache  CacheIns
	SessionId  string
	Map
	contextBase
}

func (this *SessionIns) set() {

	if this.ShortCache != nil {
		this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
	}
	if this.LongCache != nil {
		this.LongCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
	}

}

func (this *SessionIns) Session(key string, data ...interface{}) *Obj {

	if this.Map == nil {
		this.get()
	}

	if len(data) != 0 {
		if data[0] == nil {
			delete(this.Map, key)
			this.set()
		} else {
			this.Map[key] = data[0]
			this.set()
		}
		return &Obj{Data: nil}
	}

	return &Obj{Data: this.Map.Get(key)}

}

func (this *SessionIns) get() {

	if this.ShortCache != nil {
		this.Map = this.ShortCache.Cache(HEAD_SESSION_ADD + this.SessionId).ToMap()
		if this.Map != nil {
			return
		}
	}

	if this.LongCache != nil {
		this.Map = this.LongCache.Cache(HEAD_SESSION_ADD + this.SessionId).ToMap()
		if this.Map != nil {
			if this.ShortCache != nil {
				this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
			}
			return
		}
	}
	this.Map = Map{}
	this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)

	return
}

func (this *SessionIns) Init(short CacheIns, long CacheIns) {
	this.ShortCache = short
	this.LongCache = long
}
