package connector

var exampleConfig = `# XMPP-specific config for mautrix-xmpp.
#
# The homeserver, appservice, encryption and database settings are in the
# shared config section (see the default config generated by
# ` + "`--generate-example-config`" + `). This section only has XMPP settings.
#
# XMPP server to connect to (leave empty to use JID domain).
server: ""
# XMPP server port (0 = default 5222).
port: 0
# MUC (Multi-User Chat) server (leave empty = auto-detect from JID domain).
muc_server: ""
# Connect to XMPP on bridge startup.
connect_on_startup: true
# Connection timeout in seconds.
connection_timeout: 30
`

type Config struct {
	Server            string `yaml:"server"`
	Port              int    `yaml:"port"`
	MUCServer         string `yaml:"muc_server"`
	ConnectOnStartup  bool   `yaml:"connect_on_startup"`
	ConnectionTimeout int    `yaml:"connection_timeout"`
}

func (cfg *Config) GetServer(jid string) string {
	if cfg.Server != "" {
		return cfg.Server
	}
	parts := splitJID(jid)
	return parts[1]
}

func (cfg *Config) GetPort() int {
	if cfg.Port > 0 {
		return cfg.Port
	}
	return 5222
}

func (cfg *Config) GetMUCServer(jid string) string {
	if cfg.MUCServer != "" {
		return cfg.MUCServer
	}
	parts := splitJID(jid)
	if len(parts) > 1 {
		return "conference." + parts[1]
	}
	return ""
}

func (cfg *Config) GetConnectionTimeout() int {
	if cfg.ConnectionTimeout > 0 {
		return cfg.ConnectionTimeout
	}
	return 30
}

func splitJID(jid string) []string {
	for i := 0; i < len(jid); i++ {
		if jid[i] == '@' {
			return []string{jid[:i], jid[i+1:]}
		}
	}
	return []string{jid}
}
