package innerTask

import (
	"container/list"
	"netease_control_center/globals"
	"netease_control_center/interfaces/log"
	"sync"
)

type ICmdList struct {
	List   *list.List
	CurPos *list.Element
	lock   sync.RWMutex
}

func (this *ICmdList) WLock() {
	//log.Printf(log.DebugLog, "TtsList w lock\n")
	this.lock.Lock()
}

func (this *ICmdList) WUnlock() {
	//log.Printf(log.DebugLog, "TtsList w unlock\n")
	this.lock.Unlock()
}

func (this *ICmdList) RLock() {
	//log.Printf(log.DebugLog, "TtsList R lock\n")
	this.lock.RLock()
}

func (this *ICmdList) RUnlock() {
	//log.Printf(log.DebugLog, "TtsList R unlock\n")
	this.lock.RUnlock()
}

func (this *ICmdList) Init() {
	if nil == this.List {
		this.List = list.New()
	}
	this.WLock()
	defer this.WUnlock()
	this.List.Init()
	this.CurPos = nil
}

func (this *ICmdList) GetByICmd(icmd ICmd) (*list.Element, error) {
	this.RLock()
	defer this.RUnlock()

	if 0 == this.List.Len() {
		return nil, globals.List_ERR_NULL
	} else {
		for pr := this.List.Front(); nil != pr; pr = pr.Next() {
			if pr.Value.(*ICmdStruct).Cmd == icmd {
				this.CurPos = pr
				return pr, nil
			}
		}
		return nil, globals.List_ERR_SEARCH_NULL
	}
}

func (this *ICmdList) Remove(e *list.Element) {
	if nil == e {
		log.Println(log.DebugLog, "nil curpos when remove")
		return
	}
	this.WLock()
	defer this.WUnlock()

	this.List.Remove(e)
	/* only for test */
	this.Println()
}

func (this *ICmdList) Push(e interface{}) error {
	if e != nil {
		switch e.(type) {
		case *ICmdStruct:
			// 插入需要考虑顺序
			this.WLock()
			defer this.WUnlock()
			if nil == this.List {
				this.List = list.New()
			}
			this.List.PushBack(e)
		default:
			return globals.List_ERR_UNSUPPORT
		}

		/* only for test */
		this.Println()

		return nil
	}
	return globals.Tts_ERR_NODE_NULL
}

/* only for test */
func (this *ICmdList) Println() {
	log.Println(log.DebugLog, "ICmdList:")
	for pr := this.List.Front(); nil != pr; pr = pr.Next() {
		log.Printf(log.DebugLog, "cmd:%s time:%s\n",
			pr.Value.(*ICmdStruct).Cmd,
			pr.Value.(*ICmdStruct).PackTime)
	}
}
