package models

import (
	"time"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"xorm.io/xorm"
)

func (event *Event) Insert(cfg *config.Config) (err error) {
	session := cfg.Db.NewSession()
	defer session.Close()
	_, err = session.Insert(event)
	err = session.Commit()
	return
}

/*
func (event *Event) APIFormat() *APIEvent {
	if event == nil {
		return nil
	}
	return &APIEvent{
		MSgType: "none",
		IPData: {
			IP:       event.IP.IP,
			Src:      event.Src,
			Hostname: event.Hostname.String,
		},
	}
}*/

func (event *Event) APIParse(session *xorm.Session, apievent APIEvent) (err error) {
	*event = Event{
		IP:   &IP{IP: apievent.IPData.IP},
		Host: &Host{Host: apievent.IPData.Hostname},
		Src:  &Src{Src: apievent.IPData.Src},
	}
	event.IP.GetOrCreate(session)
	event.Host.GetOrCreate(session)
	event.Src.GetOrCreate(session)
	return
}

type Event struct {
	ID      int       `xorm:"pk autoincr"`
	Src     *Src      `xorm:"int src_id"`
	Host    *Host     `xorm:"int host_id"`
	IP      *IP       `xorm:"int ip_id"`
	Created time.Time `xorm:"created notnull"`
}

type APIEvent struct {
	MsgType  string `json:"msgtype"`
	Mode     string `json:"mode"`
	Hostname string `json:"hostname"`
	IPData   struct {
		IP       string `json:"ip"`
		Type     int    `json:"t"`
		Src      string `json:"src"`
		Hostname string `json:"hostname"`
		Date     string `json:"date"`
		Created  string `json:"created"`
	} `json:"ipdata"`
}
