package models

import (
	"encoding/json"
	"time"

	"cloud.o-forge.io/core/oc-lib/tools"
	"github.com/libp2p/go-libp2p/core/crypto"
)

type Event struct {
	Type string `json:"type"`
	From string `json:"from"` // peerID

	User string

	DataType  int64  `json:"datatype"`
	Timestamp int64  `json:"ts"`
	Payload   []byte `json:"payload"`
	Signature []byte `json:"sig"`
}

func NewEvent(name string, from string, dt *tools.DataType, user string, payload []byte, priv crypto.PrivKey) *Event {
	evt := &Event{
		Type:      name,
		From:      from,
		User:      user,
		Timestamp: time.Now().UTC().Unix(),
		Payload:   payload,
	}
	if dt != nil {
		evt.DataType = int64(dt.EnumIndex())
	} else {
		evt.DataType = -1
	}

	body, _ := json.Marshal(evt)
	sig, _ := priv.Sign(body)
	evt.Signature = sig
	return evt
}

func (e *Event) RawEvent() *Event {
	return &Event{
		Type:      e.Type,
		From:      e.From,
		User:      e.User,
		DataType:  e.DataType,
		Timestamp: e.Timestamp,
		Payload:   e.Payload,
	}
}

func (e *Event) ToRawByte() ([]byte, error) {
	return json.Marshal(e.RawEvent())
}
