package service

import (
	"encoding/json"
	"ext"
	log "github.com/donnie4w/go-logger/logger"
	"io/ioutil"
	"net/http"
	qu "qfw/util"
	"sync"
)

var datalock sync.Mutex

func InitRegionsService() {
	http.HandleFunc("/service/region", func(w http.ResponseWriter, r *http.Request) {
		datalock.Lock()
		data, _ := ioutil.ReadAll(r.Body)
		tmp := map[string]interface{}{}
		err := json.Unmarshal([]byte(data), &tmp)
		if err != nil {
			log.Debug(err)
		}
		ext.Ext.ExtractRegionInfo(&tmp, true)
		ext.Ext.ExtractRegionClean(&tmp)
		area := qu.ObjToString(tmp["area"])
		city := qu.ObjToString(tmp["city"])
		district := qu.ObjToString(tmp["district"])
		res, _ := json.Marshal(map[string]interface{}{
			"area":     area,
			"city":     city,
			"district": district,
		})
		w.Write(res)
		datalock.Unlock()
	})

	http.HandleFunc("/service/region/clean", func(w http.ResponseWriter, r *http.Request) {
		datalock.Lock()
		data, _ := ioutil.ReadAll(r.Body)
		tmp := map[string]interface{}{}
		err := json.Unmarshal([]byte(data), &tmp)
		if err != nil {
			log.Debug(err)
		}
		ext.Ext.ExtractRegionClean(&tmp)
		area := qu.ObjToString(tmp["area"])
		city := qu.ObjToString(tmp["city"])
		district := qu.ObjToString(tmp["district"])
		res, _ := json.Marshal(map[string]interface{}{
			"area":     area,
			"city":     city,
			"district": district,
		})
		w.Write(res)
		datalock.Unlock()
	})
}
