package domain

import "github.com/gookit/event"

type EventType string

func (et EventType) ToString() string {
	return string(et)
}

const (
	TableDataEditEvent        EventType = "table.data.edit"
	TableDataImportEvent      EventType = "table.data.import"
	TableDeleteEvent          EventType = "table.delete"
	QuerySetUpdateEvent       EventType = "table.query.set.update"
	QuerySetUpdateRenameEvent EventType = "table.query.set.update.rename"

	TableApplyOnEvent         EventType = "table.apply-on"
	QuerySetUpdateStatusEvent EventType = "table.query.set.update.status" // 禁用启用
	QuerySetDeleteEvent       EventType = "table.query.set.delete"        // 删除
)

type EventTable struct {
	Context  *Context
	Type     EventType
	Table    *Table
	QuerySet *QuerySet
	Metadata map[string]interface{}
}

func NewEventTable(ctx *Context, t EventType) *EventTable {
	return &EventTable{
		Context:  ctx,
		Type:     t,
		Metadata: make(map[string]interface{}),
	}
}
func (et *EventTable) WithContext(t *Context) *EventTable {
	et.Context = t
	return et
}
func (et *EventTable) WithType(t EventType) *EventTable {
	et.Type = t
	return et
}

func (et *EventTable) WithTable(t *Table) *EventTable {
	et.Table = t
	return et
}

func (et *EventTable) WithQuerySet(t *QuerySet) *EventTable {
	et.QuerySet = t
	return et
}

func (et *EventTable) WithMetadata(key string, values interface{}) *EventTable {
	et.Metadata[key] = values
	return et
}

func (et *EventTable) ResolveEvent(e event.Event) {
	et.Context = e.Get("Context").(*Context)
	et.Type = e.Get("Type").(EventType)
	et.Table = e.Get("Table").(*Table)
	et.QuerySet = e.Get("QuerySet").(*QuerySet)
	et.Metadata = e.Get("Metadata").(map[string]interface{})
}

func (et *EventTable) FireEvent() event.Event {
	e := event.M{}
	e["Context"] = et.Context
	e["Type"] = et.Type
	e["Table"] = et.Table
	e["QuerySet"] = et.QuerySet
	e["Metadata"] = et.Metadata
	return event.MustFire(et.Type.ToString(), e)
}