package bill

import (
	"database/sql"
	"fmt"
	"strings"
)

//Rows 模拟一个单据的rows，类似sql.Rows
type Rows struct {
	bill *Bill
	rows *sql.Rows
}

//Next 读取下一条，第一条必须调用Next后才可获取
func (b *Rows) Next() bool {
	return b.rows.Next()

}

//Err 返回最后一个操作是否有错误
func (b *Rows) Err() error {
	return b.rows.Err()
}

//Close 关闭Scaner，在读取所有的记录后也会自动关闭
func (b *Rows) Close() error {
	return b.rows.Close()
}

//Scan 扫描出当前的数据，返回的结果是Record，一个主从记录
func (b *Rows) Scan() (result *Record, err error) {
	mainRow, err := b.bill.Main.ScanMap(b.rows)
	if err != nil {
		return
	}
	result = &Record{
		Main: mainRow,
	}
	//load child
	if len(b.bill.Child) == 0 {
		return
	}
	result.Child = map[string][]map[string]interface{}{}
	mainKeyValues := b.bill.Main.KeyValues(mainRow)
	for _, tab := range b.bill.Child {
		where := []string{}
		for i := range b.bill.Main.PrimaryKeys {
			where = append(where, fmt.Sprintf("%s=?", tab.PrimaryKeys[i]))
		}
		rows, err := tab.QueryRows(strings.Join(where, " and\n"), mainKeyValues...)
		if err != nil {
			return nil, err
		}
		result.Child[tab.FullName()] = rows
	}
	return
}
