package pcap

import (
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types"
	"sync"
)

var pcaps map[string]*PcapWrapper = nil

var m *sync.Mutex

func init() {
	pcaps = make(map[string]*PcapWrapper, 0)
	m = new(sync.Mutex)
}

func GetInstance(zone *types.DiscoveryZone) (*PcapWrapper, error) {
	m.Lock()
	//
	var p *PcapWrapper
	var ok bool
	p, ok = pcaps[zone.CidrStr()]
	if !ok {
		p, err := newPcapWrapper(zone)
		if err != nil {
			m.Unlock()
			return nil, err
		}
		pcaps[zone.CidrStr()] = p
		m.Unlock()
		return p, nil
	}
	m.Unlock()
	return p, nil
}

func Release(zone *types.DiscoveryZone) {

	m.Lock()

	p, ok := pcaps[zone.CidrStr()]
	if ok == true {

		if d := p.release(); d == true {

			delete(pcaps, zone.CidrStr())
		}

	}
	m.Unlock()
}

func RemoveAll() {
	m.Lock()
	if pcaps == nil {
		m.Unlock()
		return
	}
	for k, v := range pcaps {
		v.destroy()
		delete(pcaps, k)
	}
	m.Unlock()
}
