package icsevent

import (
	"gitlab.com/cinnamon/voiceagent/icserror"
	"gitlab.com/cinnamon/voiceagent/icslog"
)

////////////////////////////////////////////////////////////////////
// round robin data structure
type RRData struct {
	data interface{}
	//data *interface{}

	tail *RRData
}

func NewRRData() *RRData {
	r := &RRData{
		tail: nil,
	}
	return r
}

func Push(first *RRData, data interface{}) *icserror.IcsError {
	if first == nil {
		return icserror.ICSERRInvalidParam
	}

	ret := NewRRData()
	ret.data = data
	var tmp *RRData

	//search end point
	cnt := 0
	for tmp = first; tmp.tail != nil; tmp = tmp.tail {
		cnt++
	}

	//assign data to end point
	tmp.tail = ret

	return nil
}

func Pop(first *RRData) (*RRData, interface{}, *icserror.IcsError) {
	if first == nil {
		return nil, nil, icserror.ICSERRInvalidParam
	}

	//l := icslog.GetIcsLog()

	ftail := first.tail

	ret := first.tail

	if ret != nil && ret.data != nil {
	} else {
		return first, nil, nil
	}
	first = ftail

	return first, ret.data, nil
}

func (r *RRData) GetData() interface{} {
	return r.data
}

func GetLength(first *RRData) (int, *icserror.IcsError) {
	if first == nil {
		return -1, icserror.ICSERRInvalidParam
	}

	l := icslog.GetIcsLog()
	var iter int = 0
	for tmp := first; tmp != nil && tmp.tail != nil; tmp = tmp.tail {
		var id int
		h := NewEventH()
		switch v := tmp.data.(type) {
		case int:
			id = v
		}
		p := h.getEvt(id)
		l.Printf(icslog.LOG_LEVEL_DEBUG2, -1, "GetLength(%d)>%d-%v tmp>%p-%p", iter, id, p, tmp, tmp.tail)

		iter++
	}

	return iter, nil
}
