/ac/codec_manager.go
package ac

import (
	"io"
)

type CodecManager interface {
	AddModel(context ModelContext, model Model)
	Encode(context ModelContext, symbol uint32)
	Decode(context ModelContext) uint32
	Finish()
}

type ModelContext int

type codecManager struct {
	ac Codec
	source io.Reader
	target io.Writer
	encoding bool
	models map[ModelContext]Model
}

func NewEncoder(target io.Writer) (CodecManager, error) {
	e := &codecManager{
		NewCodec(),
		nil,
		target,
		true,
		make(map[ModelContext]Model),
	}

	e.ac.SetFileOutput(target)

	return e, nil
}

func NewDecoder(source io.Reader) (CodecManager, error) {
	e := &codecManager{
		NewCodec(),
		source,
		nil,
		false,
		make(map[ModelContext]Model),
	}

	e.ac.SetFileInput(source)
	e.ac.DecodeStart()

	return e, nil
}

func (self *codecManager) AddModel(context ModelContext, model Model) {
	self.models[context] = model
}

func (self *codecManager) Encode(context ModelContext, symbol uint32) {
	self.models[context].Encode(self.ac, symbol)
}

func (self *codecManager) Finish() {
	if self.encoding {
		self.ac.EncodeFinish()
	}
}

func (self *codecManager) Decode(context ModelContext) uint32 {
	return self.models[context].Decode(self.ac)
}