package models

import (
	"time"

	"xorm.io/xorm"
)

func (as *AutonomousSystem) GetOrCreate(session *xorm.Session) (apias *APIAutonomousSystem, err error) {
	has, err := session.Get(as)
	if err != nil {
		return
	}
	if !has {
		session.Insert(as)
	} else {
		session.ID(as.ID).Update(as)
	}
	as.Get(session)
	apias = as.APIFormat()
	return
}

func (as *AutonomousSystem) Get(session *xorm.Session) (apias *APIAutonomousSystem, err error) {
	has, err := session.Get(as)
	if !has || err != nil {
		return
	}
	apias = as.APIFormat()
	return
}

func (as *AutonomousSystem) APIFormat() *APIAutonomousSystem {
	if as == nil {
		return &APIAutonomousSystem{}
	}
	return &APIAutonomousSystem{
		ASID:   as.ASID,
		ASName: as.ASName,
	}
}

func (as *AutonomousSystem) APIParse(apias APIAutonomousSystem) (err error) {
	*as = AutonomousSystem{
		ASID:   apias.ASID,
		ASName: apias.ASName}
	return
}

type AutonomousSystem struct {
	ID      int       `xorm:"pk autoincr"`
	ASID    int       `xorm:"integer unique(asindex) as_id"`
	ASName  string    `xorm:"text unique(asindex) as_name"`
	Created time.Time `xorm:"created notnull"`
	Updated time.Time `xorm:"updated notnull"`
}

type APIAutonomousSystem struct {
	ID     int    `json:"-"`
	ASID   int    `json:"as_id"`
	ASName string `json:"as_name"`
}
