package types

import (
	"git.loafle.net/overflow/overflow_probe/discovery/util/converter"
	"github.com/cihub/seelog"
	"net"
	"strconv"
	"sync"
)

type discoverTestZoneCallback func(host *DiscoveryZone)

type DiscoveryZone struct {
	ID             int                `json:"id,omitempty"`
	Ip             int64              `json:"ip"`
	Netmask        uint8              `json:"mask"`
	Iface          string             `json:"iface"`
	Mac            int64              `json:"mac"`
	FirstScanRange int64              `json:"firstScanRange"`
	LastScanRange  int64              `json:"lastScanRange"`
	Histories      []*HostScanHistory `json:"-"`
	Hosts          []*DiscoveryHost   `json:"hosts"`
	CurrentTypes   string             `json:"-"`

	Hosts_ map[string]*DiscoveryHost `json:"-"`
	M      *sync.RWMutex             `json:"-"`
}

func (z *DiscoveryZone) SetHost(ip string, value *DiscoveryHost) {
	z.M.Lock()
	defer z.M.Unlock()
	z.Hosts_[ip] = value
}

func (z *DiscoveryZone) GetHost(ip string) (*DiscoveryHost, bool) {
	z.M.RLock()
	defer z.M.RUnlock()
	h, ok := z.Hosts_[ip]
	return h, ok
}

func (p *DiscoveryZone) AddHistory(h *HostScanHistory) {
	p.Histories = append(p.Histories, h)
}

func (z *DiscoveryZone) CidrStr() string {
	tempIp := converter.IntToIP4(z.Ip)
	tempNet := int(z.Netmask)
	netmask := strconv.Itoa(tempNet)
	str := tempIp.String() + "/" + netmask

	_, ipnet, err := net.ParseCIDR(str)

	if err != nil {
		seelog.Critical(err)
	}
	return ipnet.String()
}

func (z *DiscoveryZone) CidrInt64() int64 {
	return converter.CidrToInt64(z.CidrStr())
}
