package conf

import (
	"encoding/xml"
	"io/ioutil"
	"strconv"
	"strings"
	_ "strings"

	"common/logger"
)

type MysqlConf struct {
	Ip           string `xml:",attr"`
	Port         int    `xml:",attr"`
	User         string `xml:",attr"`
	Pwd          string `xml:",attr"`
	Database     string `xml:",attr"`
	LoadInterval int    `xml:",attr"`
}

type Rooms struct {
	XMLName   xml.Name   `xml:"Rooms"`
	RoomItems []TestRoom `xml:"RoomItem"`
}
type TestRoom struct {
	XMLName xml.Name `xml:"RoomItem"`
	IDs     string   `xml:",attr"`
	ArrIDs  []int
}

type Observers struct {
	XMLName      xml.Name   `xml:"Observers"`
	ObserverList []Observer `xml:"Observer"`
}
type Observer struct {
	XMLName xml.Name `xml:"Observer"`
	IDs     string   `xml:",attr"`
}

type TestConf struct {
	GameDB      MysqlConf `xml:"GameDB"`
	Rooms       Rooms     `xml:"Rooms"`
	Observers   Observers `xml:"Observers"`
	ObserverMap map[int]int
}

var (
	Config = new(TestConf)
)

func ParseIDs() {
	for idx, room := range Config.Rooms.RoomItems {
		s := strings.Split(room.IDs, ",")
		for _, id := range s {
			rid, _ := strconv.Atoi(id)
			Config.Rooms.RoomItems[idx].ArrIDs = append(Config.Rooms.RoomItems[idx].ArrIDs, rid)
		}
	}
	Config.ObserverMap = map[int]int{}
	for _, ob := range Config.Observers.ObserverList {
		s := strings.Split(ob.IDs, ",")
		for _, id := range s {
			rid, _ := strconv.Atoi(id)
			Config.ObserverMap[rid] = rid
		}
	}
}

func LoadConf(filename string) error {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		logger.Info("read file:%+v, error:%+v", filename, err)
		return err
	}
	logger.Info("conf xml:%+v", string(content))
	err = xml.Unmarshal(content, Config)
	if err != nil {
		logger.Info("decode xml error:%+v", err)
		return err
	}
	ParseIDs()
	DumpConf()
	return nil
}

func DumpConf() {
	logger.Info("--------------config dump----start--------")
	logger.Info("rooms:%+v", Config.Rooms)
	logger.Info("--------------config dump----end--------")
}

func GetGameDBConf() MysqlConf {
	return Config.GameDB
}
