package models

import (
	"time"

	"xorm.io/xorm"
)

func (host *Host) GetOrCreate(session *xorm.Session) (apihost *APIHost, err error) {
	has, err := session.Get(host)
	if err != nil {
		return
	}
	if !has {
		session.Insert(host)
	} else {
		session.ID(host.ID).Update(host)
	}
	host.Get(session)
	apihost = host.APIFormat()
	return
}

func (host *Host) Get(session *xorm.Session) (apihost *APIHost, err error) {
	has, err := session.Get(host)
	if !has || err != nil {
		return
	}
	apihost = host.APIFormat()
	return
}

func (host *Host) APIFormat() *APIHost {
	if host == nil {
		return &APIHost{}
	}
	return &APIHost{
		Host: host.Host,
	}
}

func (host *Host) APIParse(apihost APIHost) (err error) {
	*host = Host{
		Host: apihost.Host}
	return
}

type Host struct {
	ID      int       `xorm:"pk autoincr"`
	Host    string    `xorm:"text unique host" json:"host"`
	Created time.Time `xorm:"created notnull"`
	Updated time.Time `xorm:"updated notnull"`
}

type APIHost struct {
	ID   int    `json:"-"`
	Host string `json:"host"`
}
