package models

import (
	"time"

	"xorm.io/xorm"
)

func (country *Country) GetOrCreate(session *xorm.Session) (apicountry *APICountry, err error) {
	has, err := session.Get(country)
	if err != nil {
		return
	}
	if !has {
		session.Insert(country)
	} else {
		session.ID(country.ID).Update(country)
	}
	apicountry = country.APIFormat()
	country.Get(session)
	return
}

func (country *Country) Get(session *xorm.Session) (apicountry *APICountry, err error) {
	has, err := session.Get(country)
	if !has || err != nil {
		return
	}
	apicountry = country.APIFormat()
	return
}

func (country *Country) APIFormat() *APICountry {
	if country == nil {
		return &APICountry{}
	}
	return &APICountry{
		CountryName: country.CountryName,
	}
}

func (country *Country) APIParse(apicountry APICountry) (err error) {
	*country = Country{
		CountryName: apicountry.CountryName}
	return
}

type Country struct {
	ID          int       `xorm:"pk autoincr"`
	CountryName string    `xorm:"text unique(countryindex) country_name" json:"country_name"`
	Created     time.Time `xorm:"created notnull"`
	Updated     time.Time `xorm:"updated notnull"`
}

type APICountry struct {
	ID          int    `json:"-"`
	CountryName string `json:"country_name"`
}
