package models

import (
	"time"

	"xorm.io/xorm"
)

func (city *City) GetOrCreate(session *xorm.Session) (apicity *APICity, err error) {
	has, err := session.Get(city)
	if err != nil {
		return
	}
	if !has {
		session.Insert(city)
	} else {
		session.ID(city.ID).Update(city)
	}
	city.Get(session)
	apicity = city.APIFormat()
	return
}

func (city *City) Get(session *xorm.Session) (apicity *APICity, err error) {
	has, err := session.Get(city)
	if !has || err != nil {
		return
	}
	apicity = city.APIFormat()
	return
}

func (city *City) APIFormat() *APICity {
	if city == nil {
		return &APICity{}
	}
	return &APICity{
		CityName: city.CityName,
	}
}

func (city *City) APIParse(apicity APICity) (err error) {
	*city = City{
		CityName: apicity.CityName}
	return
}

type City struct {
	ID       int       `xorm:"pk autoincr"`
	CityName string    `xorm:"text unique(cityindex) city_name" json:"city_name"`
	Created  time.Time `xorm:"created notnull"`
	Updated  time.Time `xorm:"updated notnull"`
}

type APICity struct {
	ID       int    `json:"-"`
	CityName string `json:"city_name"`
}
