package models

import (
	"time"

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

func (sr *ScanResult) GetOrCreate(cfg *config.Config) (apisr *APIScanResult, err error) {
	has, err := cfg.Db.Get(sr)
	if !has {
		cfg.Db.Insert(sr)
	} else {
		cfg.Db.ID(sr.ID).Update(sr)
	}
	sr.Get(cfg)
	apisr = sr.APIFormat()
	return
}

func (sr *ScanResult) Get(cfg *config.Config) (apisr *APIScanResult, err error) {
	has, err := cfg.Db.Get(sr)
	if !has || err != nil {
		return
	}
	apisr = sr.APIFormat()
	return
}

func (sr *ScanResult) APIFormat() *APIScanResult {
	if sr == nil {
		return &APIScanResult{}
	}
	return &APIScanResult{
		Protocol:    sr.Protocol,
		PortID:      sr.PortID,
		State:       sr.State,
		ServiceName: sr.ServiceName,
	}
}

func (sr *ScanResult) APIParse(apisr APIScanResult) (err error) {
	*sr = ScanResult{
		Protocol: apisr.Protocol,
		PortID:   apisr.PortID}
	return
}

type ScanResult struct {
	ID          int       `xorm:"pk autoincr"`
	Protocol    string    `xorm:"text default ''"`
	PortID      int       `xorm:"default ''"`
	State       string    `xorm:"text default ''"`
	ServiceName string    `xorm:"text default ''"`
	Created     time.Time `xorm:"created notnull"`
	Updated     time.Time `xorm:"updated notnull"`
}

type APIScanResult struct {
	ID          int    `json:"id"`
	Protocol    string `json:"proto"`
	PortID      int    `json:"port_id"`
	State       string `json:"state"`
	ServiceName string `json:"service"`
}
