package bill

import (
	"bytes"
	"encoding/gob"

	"github.com/linlexing/dbx/schema"
)

//Record 代表一个单据记录，一个主表记录和N个明细表记录集组成
type Record struct {
	Main  map[string]interface{}
	Child map[string][]map[string]interface{}
}

func init() {
	gob.Register(new(Record))
}

//IsEmpty 返回是否为空记录
func (b *Record) IsEmpty() bool {
	return b.Main == nil
}

//Scan 将一个记录扫描到struct中
func (b *Record) Scan(out interface{}) error {
	return schema.Row2Struct(b.Main, b.Child, out)
}

//Encode 将Record压缩为byte数组
func (b *Record) Encode() ([]byte, error) {
	out := bytes.NewBuffer(nil)
	if err := gob.NewEncoder(out).Encode(b); err != nil {
		return nil, err
	}
	return out.Bytes(), nil
}

//DecodeRecord 从一个字节数组解压
func DecodeRecord(in []byte) (*Record, error) {
	bys := bytes.NewBuffer(in)
	out := new(Record)
	if err := gob.NewDecoder(bys).Decode(out); err != nil {
		return nil, err
	}
	return out, nil
}

//ParseRecord 根据一个struct，返回一个Record
func ParseRecord(in interface{}) (rec *Record, err error) {
	rec = &Record{}
	rec.Main, rec.Child, err = schema.Struct2Row(in)
	return
}
