package parsers

import (
	"regexp"

	"github.rackspace.com/gorax/tools/util"
)

var (
	configSyncRoleRe        = regexp.MustCompile(`config-sync\s+mode\s+(\S+)\s*\n`)
	configSyncRole124Re     = regexp.MustCompile(`config-sync\s+(\S+)\s+ethernet\s+`)
	portBlockRe             = regexp.MustCompile(`server\s+port\s+(\d+)\s*\n((?:.|\n)*?\n(?:\n|!))`)
	portTCPRe               = regexp.MustCompile(`tcp\s*?\n`)
	portUDPRe               = regexp.MustCompile(`udp\s*?\n`)
	portTCPKeepaliveRe      = regexp.MustCompile(`tcp\s+keepalive\s+(.*?)\s*?\n`)
	portUDPKeepaliveRe      = regexp.MustCompile(`udp\s+keepalive\s+(.*?)\s*?\n`)
	portSessionSyncRe       = regexp.MustCompile(`session-sync\s*?\n`)
	sslSimpleHealthCheckKRe = regexp.MustCompile(`no\s+server\s+use-simple-ssl-health-check\s*?\n`)
	sNATRe                  = regexp.MustCompile(`server\s+source-nat-ip\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*?)\s*\n`)
	sNATPortRangeRe         = regexp.MustCompile(`port-range\s+(\d+)`)
	sNATPortAllocRe         = regexp.MustCompile(`port-alloc-per-real`)
)

type (
	// AdxGlobalServer defines all the global-server configuration items
	// on an ADX
	AdxGlobalServer struct {
		BPMask               string          `json:"bp_mask"`
		SyncRole             string          `json:"config_sync_role"`
		Ports                []AdxServerPort `json:"server_ports"`
		SimpleSSLHealthCheck bool            `json:"simple_ssl_healthcheck"`
		SNATs                []AdxSNAT       `json:"source_nat_ip"`
	}
	// AdxServerPort is a parser type for the server port configuration items
	// at the global level
	AdxServerPort struct {
		Number       int    `json:"number"`
		TCP          bool   `json:"tcp"`
		UDP          bool   `json:"udp"`
		TCPKeepalive string `json:"tcp_keepalive"`
		UDPKeepalive string `json:"udp_keepalive"`
		SessionSync  bool   `json:"session_sync"`
	}
	// AdxSNAT is a parser type for the source-nat configuration items
	// at the global level
	AdxSNAT struct {
		IPAddress string `json:"ip_address"`
		Netmask   string `json:"netmask"`
		Source    string `json:"source"`
		PortRange int    `json:"port_range"`
		PortAlloc bool   `json:"port_alloc_per_real"`
	}
)

// Parse method is used to implement type population of a given string
// using parsers to populate the method receiver.
func (a *AdxGlobalServer) Parse(s *string) AdxGlobalServer {
	a.BPMask = util.RegexpFindString(bpMaskRe, *s)
	a.SimpleSSLHealthCheck = !findStringBool(sslSimpleHealthCheckKRe, *s)
	syncRole := util.RegexpFindString(configSyncRoleRe, *s)
	if syncRole == "" {
		a.SyncRole = util.RegexpFindString(configSyncRole124Re, *s)
	} else {
		a.SyncRole = syncRole
	}
	for _, p := range portBlockRe.FindAllStringSubmatch(*s, -1) {
		a.Ports = append(a.Ports, AdxServerPort{
			Number:       util.Atoi(p[1]),
			TCP:          findStringBool(portTCPRe, p[2]),
			UDP:          findStringBool(portUDPRe, p[2]),
			TCPKeepalive: util.RegexpFindString(portTCPKeepaliveRe, p[2]),
			UDPKeepalive: util.RegexpFindString(portUDPKeepaliveRe, p[2]),
			SessionSync:  findStringBool(portSessionSyncRe, p[2]),
		})
	}
	for _, sNat := range sNATRe.FindAllStringSubmatch(*s, -1) {
		a.SNATs = append(a.SNATs, AdxSNAT{
			IPAddress: sNat[1],
			Netmask:   sNat[2],
			Source:    sNat[3],
			PortRange: util.RegexpAtoInt(sNATPortRangeRe, sNat[4]),
			PortAlloc: findStringBool(sNATPortAllocRe, sNat[4]),
		})
	}
	return *a

}

func findStringBool(re *regexp.Regexp, s string) bool {
	x := re.FindStringSubmatch(s)
	if x == nil {
		return false
	} else {
		return true
	}
}
