//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package sql

import (
	"fmt"

	"github.com/88250/lute/ast"
	"github.com/siyuan-note/siyuan/kernel/av"
	"github.com/siyuan-note/siyuan/kernel/util"
)

func RenderAttributeViewTable(attrView *av.AttributeView, view *av.View, query string, depth *int, cachedAttrViews map[string]*av.AttributeView) (ret *av.Table) {
	viewable := attrView.RenderedViewables[view.ID]
	if nil != viewable {
		ret = viewable.(*av.Table)
		return
	}

	ret = &av.Table{
		BaseInstance: av.NewViewBaseInstance(view),
		Columns:      []*av.TableColumn{},
		Rows:         []*av.TableRow{},
	}

	// 组装列
	for _, col := range view.Table.Columns {
		key, getErr := attrView.GetKey(col.ID)
		if nil != getErr {
			// 找不到字段则在视图中删除
			removeMissingField(attrView, view, col.ID)
			continue
		}

		ret.Columns = append(ret.Columns, &av.TableColumn{
			BaseInstanceField: &av.BaseInstanceField{
				ID:           key.ID,
				Name:         key.Name,
				Type:         key.Type,
				Icon:         key.Icon,
				Wrap:         col.Wrap,
				Hidden:       col.Hidden,
				Desc:         key.Desc,
				Calc:         col.Calc,
				Options:      key.Options,
				NumberFormat: key.NumberFormat,
				Template:     key.Template,
				Relation:     key.Relation,
				Rollup:       key.Rollup,
				Date:         key.Date,
				Created:      key.Created,
				Updated:      key.Updated,
			},
			Width: col.Width,
			Pin:   col.Pin,
		})
	}

	rowsValues := generateAttrViewItems(attrView, view) // 生成行
	filterNotFoundAttrViewItems(rowsValues)             // 过滤掉不存在的行

	// 生成行单元格
	for rowID, rowValues := range rowsValues {
		var tableRow av.TableRow
		for _, col := range ret.Columns {
			var tableCell *av.TableCell
			for _, keyValues := range rowValues {
				if keyValues.Key.ID == col.ID {
					tableCell = &av.TableCell{
						BaseValue: &av.BaseValue{
							ID:        keyValues.Values[0].ID,
							Value:     keyValues.Values[0],
							ValueType: col.Type,
						},
					}
					break
				}
			}
			if nil == tableCell {
				tableCell = &av.TableCell{
					BaseValue: &av.BaseValue{
						ID:        rowID[:14] + ast.NewNodeID()[14:],
						ValueType: col.Type,
					},
				}
			}
			tableRow.ID = rowID

			filedDateIsTime := false
			if nil != col.Date {
				filedDateIsTime = col.Date.FillSpecificTime
			}
			fillAttributeViewBaseValue(tableCell.BaseValue, col.ID, rowID, col.NumberFormat, col.Template, filedDateIsTime)
			tableRow.Cells = append(tableRow.Cells, tableCell)
		}
		ret.Rows = append(ret.Rows, &tableRow)
	}

	// 回填补全数据
	fillAttributeViewKeyValues(attrView, ret)

	// 批量获取块属性以提升性能
	var ialIDs []string
	for _, row := range ret.Rows {
		blockVal := row.GetBlockValue()
		if nil != blockVal && !blockVal.IsDetached {
			ialIDs = append(ialIDs, blockVal.Block.ID)
		}
	}
	ials := BatchGetBlockAttrs(ialIDs)

	// 渲染自动生成的字段值，比如关联、汇总、创建时间和更新时间
	fillAttributeViewAutoGeneratedValues(attrView, ret, ials, depth, cachedAttrViews)

	// 最后渲染模板字段，这样模板就可以使用汇总、关联、创建时间和更新时间的值了
	renderTemplateErr := fillAttributeViewTemplateValues(attrView, view, ret, ials)
	if nil != renderTemplateErr {
		util.PushErrMsg(fmt.Sprintf(util.Langs[util.Lang][44], util.EscapeHTML(renderTemplateErr.Error())), 30000)
	}

	filterByQuery(query, ret)
	manualSort(view, ret)
	return
}
