package area

import (
	_ "embed"
	"encoding/json"
)

type ProvinceCity struct {
	Provinces     []*Province
	Cities        []*City
	ProvincesCity map[string][]*City
}

func (p *ProvinceCity) LoadProvincesCity(provinces []*Province, cities []*City) {
	p.Provinces = provinces
	p.Cities = cities
	for i := range provinces {
		p.ProvincesCity[provinces[i].Province] = make([]*City, 0)
	}
	for i := range cities {
		if _, ok := p.ProvincesCity[cities[i].Province]; ok {
			p.ProvincesCity[cities[i].Province] = append(p.ProvincesCity[cities[i].Province], cities[i])
		}
	}
}

var DefaultProvinceCity *ProvinceCity

// data source :https://github.com/uiwjs/province-city-china/tree/gh-pages

//go:embed city.json
var city []byte

//go:embed province.json
var province []byte

func SetUp() {
	DefaultProvinceCity = &ProvinceCity{
		Provinces:     make([]*Province, 0),
		Cities:        make([]*City, 0),
		ProvincesCity: make(map[string][]*City),
	}
	var cities []*City = make([]*City, 0)
	var provinces []*Province = make([]*Province, 0)
	err := json.Unmarshal(city, &cities)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(province, &provinces)
	if err != nil {
		panic(err)
	}
	DefaultProvinceCity.LoadProvincesCity(provinces, cities)
}

/*
eg:
{
    "code": "130100",
    "name": "石家庄市",
    "province": "13",
    "city": "01"
}
*/
type City struct {
	Code     string `json:"code"`
	Name     string `json:"name"`
	Province string `json:"province"`
	City     string `json:"city"`
}

/*
eg:
{
    "code": "110000",
    "name": "北京市",
    "province": "11"
}
*/
type Province struct {
	Code     string `json:"code"`
	Name     string `json:"name"`
	Province string `json:"province"`
}

func Provinces() []*Province {
	return DefaultProvinceCity.Provinces
}

func Cities() []*City {
	return DefaultProvinceCity.Cities
}

func ProvinceCities(provinceCode string) []*City {
	if v, ok := DefaultProvinceCity.ProvincesCity[provinceCode]; ok {
		return v
	}
	return []*City{}
}