package parsers

import (
	"net"
	"regexp"
	"strconv"

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

// used with "sh run int"
var (
	runningMgmtIntRe = regexp.MustCompile(`interface\s+management\s+(\d+)\s*\n((.|\n)*?)!`)
	runningEthIntRe  = regexp.MustCompile(`interface\s+ethernet\s+(\d+)\s*\n((.|\n)*?)!`)
	runningVEIntRe   = regexp.MustCompile(`interface\s+ve\s+(\d+)\s*\n((.|\n)*?!)`)
	ipAddressRe      = regexp.MustCompile(`ip\s+address\s+(\S+)`)
	netmaskRe        = regexp.MustCompile(`ip\s+address\s+\S+\s+(\S+)`)
	ipv6AddressRe    = regexp.MustCompile(`ipv6\s+address\s+(\S+?)/\d+`)
	ipv6CIDRRe       = regexp.MustCompile(`ipv6\s+address\s+\S+?/(\d+)`)
	dhcpClientRe     = regexp.MustCompile(`dhcp-client\s+(\S+)`)
	disabledStateRe  = regexp.MustCompile(`\s+(disable)\s*\n`)
	enabledStateRe   = regexp.MustCompile(`\s+(enable)\s*\n`)
	speedDuplexRe    = regexp.MustCompile(`speed-duplex\s+(\S+)`)
	vipGroupRe       = regexp.MustCompile(`vip-group\s+(\d+)`)
	ipVRIDRe         = regexp.MustCompile(`ip\s+vrrp-extended\s+vrid\s+(\d+)\s*\n((.|\n)*?)(!|\sipv6)`)
	ipv6VRIDRe       = regexp.MustCompile(`ipv6\s+vrrp-extended\s+vrid\s+(\d+)\s*\n((.|\n)*?)!`)
	virtualIPRe      = regexp.MustCompile(`ip[ -]address\s+(\S+)`)
	backupPriorityRe = regexp.MustCompile(`backup\s+priority\s+(\d+)`)
	trackPriorityRe  = regexp.MustCompile(`track-priority\s+(\d+)`)
	trackPortRe      = regexp.MustCompile(`track-port\s+e\s+(\d+)`)
)

type (
	// AdxRunningInterfaces aggregates all interface types and listing into
	// a single parent struct
	AdxRunningInterfaces struct {
		MgmtInterface []AdxRunMgmtInterface `json:"management_interfaces"`
		EthInterface  []AdxRunEthInterface  `json:"ethernet_interfaces"`
		VEInterface   []AdxRunVEInterface   `json:"ve_interfaces"`
	}

	// AdxRunMgmtInterface defines parsed details about an ADX management interface
	AdxRunMgmtInterface struct {
		Interface  int    `json:"interface"`
		IPAddress  string `json:"ip_address"`
		NetMask    string `json:"netmask"`
		DHCPClient string `json:"dhcp-client status"`
	}

	// AdxRunEthInterface defines parsed details about an ADX ethernet interface
	AdxRunEthInterface struct {
		Interface   int    `json:"interface"`
		IPAddress   string `json:"ip_address"`
		NetMask     string `json:"netmask"`
		SpeedDuplex string `json:"speed-duplex"`
		State       string `json:"state"`
	}

	// AdxRunVEInterface defines parsed details about an ADX virtual interface
	AdxRunVEInterface struct {
		Interface   int          `json:"interface"`
		IPAddress   string       `json:"ip_address"`
		NetMask     string       `json:"netmask"`
		IPv6Address string       `json:"ipv6_address"`
		IPv6CIDR    *int         `json:"ipv6_cidr"`
		IPv4VRID    AdxVEIntVRID `json:"ipv4_vrid"`
		IPv6VRID    AdxVEIntVRID `json:"ipv6_vrid"`
	}

	// AdxVEIntVRID defines parsed details about an ADX virtual IP interface
	AdxVEIntVRID struct {
		ID            int                `json:"id"`
		VirtualIP     string             `json:"virtual_ip_address"`
		Priority      string             `json:"priority"`
		TrackPriority string             `json:"track-priority"`
		TrackPort     []AdxVRRPTrackPort `json:"track-ports"`
		VipGroup      *int               `json:"vip-group"`
		State         string             `json:"vrid_state"`
	}
)

// Parse method is used to implement type population of a given string
// using parsers to populate the method receiver.
func (a *AdxRunningInterfaces) Parse(s *string) {
	for _, v := range runningMgmtIntRe.FindAllStringSubmatch(*s, -1) {
		var i AdxRunMgmtInterface
		i.Interface = util.Atoi(v[1])
		i.parse(v[2])
		a.MgmtInterface = append(a.MgmtInterface, i)
	}

	for _, v := range runningEthIntRe.FindAllStringSubmatch(*s, -1) {
		var i AdxRunEthInterface
		i.Interface = util.Atoi(v[1])
		i.parse(v[2])
		a.EthInterface = append(a.EthInterface, i)
	}

	for _, v := range runningVEIntRe.FindAllStringSubmatch(*s, -1) {
		var i AdxRunVEInterface
		i.Interface = util.Atoi(v[1])
		i.parse(v[2])
		a.VEInterface = append(a.VEInterface, i)
	}
}

func (i *AdxRunMgmtInterface) parse(s string) {
	i.IPAddress = util.RegexpString(ipAddressRe, s)
	i.NetMask = util.RegexpString(netmaskRe, s)
	i.DHCPClient = util.RegexpString(dhcpClientRe, s)
}

func (i *AdxRunEthInterface) parse(s string) {
	i.IPAddress = util.RegexpString(ipAddressRe, s)
	i.NetMask = util.RegexpString(netmaskRe, s)
	i.SpeedDuplex = util.RegexpString(speedDuplexRe, s)
	i.State = util.RegexpString(disabledStateRe, s)
}

func (i *AdxRunVEInterface) parse(s string) {
	i.IPAddress = util.RegexpString(ipAddressRe, s)
	i.NetMask = util.RegexpString(netmaskRe, s)
	i.IPv6Address = util.RegexpFindString(ipv6AddressRe, s)
	i.IPv6CIDR = util.RegexpAtoiPtr(ipv6CIDRRe, s)
	i.IPv4VRID = parseVRID(ipVRIDRe, s)
	i.IPv6VRID = parseVRID(ipv6VRIDRe, s)
}

func parseVRID(re *regexp.Regexp, s string) AdxVEIntVRID {
	var v AdxVEIntVRID
	x := re.FindStringSubmatch(s)
	if x == nil {
		return v
	}

	v.ID, _ = strconv.Atoi(x[1])
	v.VirtualIP = util.RegexpString(virtualIPRe, x[2])
	v.Priority = util.RegexpString(backupPriorityRe, x[2])
	v.TrackPriority = util.RegexpString(trackPriorityRe, x[2])
	for _, tp := range trackPortRe.FindAllStringSubmatch(x[2], -1) {
		v.TrackPort = append(v.TrackPort, AdxVRRPTrackPort{IntNum: tp[1]})
	}
	v.VipGroup = util.RegexpAtoiPtr(vipGroupRe, x[2])
	v.State = util.RegexpFindString(enabledStateRe, x[2])

	return v
}

// VeNetwork function returns a net.IPNet type for the matching ve in a
// list of ves
func VeNetwork(ve int, vl []AdxRunVEInterface) *net.IPNet {
	for _, i := range vl {
		if i.Interface == ve {
			if ipn, err := util.IPNetwork(i.IPAddress, i.NetMask); err == nil {
				return ipn
			}
		}
	}
	return nil
}

// MgmtNetwork function returns a net.IPNet type for the matching management ID in a
// list of management interfaces
func MgmtNetwork(mgmt int, ml []AdxRunMgmtInterface) *net.IPNet {
	for _, m := range ml {
		if m.Interface == mgmt {
			if ipn, err := util.IPNetwork(m.IPAddress, m.NetMask); err == nil {
				return ipn
			}
		}
	}
	return nil
}

// EthernetNetwork function returns a net.IPNet type for the matching ethernet ID in a
// list of ethernet interfaces
func EthernetNetwork(eth int, el []AdxRunEthInterface) *net.IPNet {
	for _, e := range el {
		if e.Interface == eth {
			if ipn, err := util.IPNetwork(e.IPAddress, e.NetMask); err == nil {
				return ipn
			}
		}
	}
	return nil
}
