package presenter

// |@@| C

import (
	"fmt"
	erro "gardening/src/lib/error"
	"slices"
	"strings"
)

type Presenter struct {
}

func (this *Presenter) FilteredColumns(columns []*Column, filter string) []*Column {
	var filtered []*Column

	for _, column := range columns {
		if filter == "main" && column.Main == false {
			continue
		}
		if filter == "sub" && column.Sub == false {
			continue
		}
		filtered = append(filtered, column)
	}
	return filtered
}

func (this *Presenter) FilterColumnsByKeys(columns []*Column, keys []string) []*Column {
	var filtered []*Column

	for _, column := range columns {
		if !slices.Contains(keys, column.Key) {
			continue
		}
		filtered = append(filtered, column)
	}
	return filtered
}

func (this *Presenter) FindFormFieldByKey(key string, fields []*FormField) (*FormField, error) {
	for _, field := range fields {
		if field.Key == key {
			return field, nil
		}
	}
	return nil, erro.N("Cannot find field").KV("key", key)
}

func (this *Presenter) RemoveColumnsByKeys(columns []*Column, keys []string) []*Column {
	var filtered []*Column

	for _, column := range columns {
		if slices.Contains(keys, column.Key) {
			continue
		}
		filtered = append(filtered, column)
	}
	return filtered
}

func (this *Presenter) NameViaIndexes(name string, formField *FormField) string {
	args := make([]any, len(formField.Indexes))
	for i, v := range formField.Indexes {
		args[i] = v
	}
	return fmt.Sprintf(name, args...)
}

func (this *Presenter) TransformIntoTree(formFields []*FormField) []*FormField {
	m := make(map[string]*FormField)
	for _, formField := range formFields {
		m[formField.Key] = formField
	}
	for _, formField := range formFields {
		ss := strings.Split(formField.Key, ".")
		if len(ss) == 1 {
			continue
		}
		parentKey := strings.Join(ss[:len(ss)-1], ".")
		parent, has := m[parentKey]
		if !has {
			panic(erro.N("Cannot find parent form field").KV("parent_key", parentKey).KV("key", formField.Key))
		}
		parent.Children = append(parent.Children, formField)
	}
	var rootFields []*FormField
	for _, formField := range formFields {
		ss := strings.Split(formField.Key, ".")
		if len(ss) != 1 {
			continue
		}
		rootFields = append(rootFields, formField)
	}
	return rootFields
}

func (this *Presenter) FindTemplatesByKeyPrefix(prefix string, formFields []*FormField) []*FormField {
	var set []*FormField
	for _, formField := range formFields {
		if strings.HasPrefix(formField.Key+".", prefix) {
			set = append(set, formField)
		}
	}
	return set
}

func (this *Presenter) FormFieldFromTemplate(template *FormField, indexes []int) *FormField {
	return &FormField{
		Key:     template.Key,
		Label:   template.Label,
		Hidden:  template.Hidden,
		Value:   template.Value,
		Data:    template.Data,
		Indexes: indexes,
	}
}

func (this *Presenter) TrimTemplates(fields []*FormField) []*FormField {
	var set []*FormField
	for _, field := range fields {
		if field.Template == true {
			continue
		}
		set = append(set, field)
	}
	return set
}
