package main

import (
	"sync/atomic"
	"unsafe"

	"sync"

	"github.com/cespare/xxhash"
)

var (
	emptyBytes = []byte("")
)

const (
	MaxCount = 65535
)

func hashFunc(ip string) uint64 {
	return xxhash.Sum64String(ip) & MaxCount
}

type ipMap struct {
	m map[string]int
	sync.Mutex
}

func (m *ipMap) add(ip string, max int) bool {
	m.Lock()
	defer m.Unlock()
	if v, ok := m.m[ip]; ok {
		if v >= max {
			return false
		}
		m.m[ip]++
		return true
	}
	m.m[ip] = 1
	return true
}

func (m *ipMap) sub(ip string) {
	m.Lock()
	defer m.Unlock()
	if v, ok := m.m[ip]; ok {
		if v > 1 {
			m.m[ip]--
		} else {
			delete(m.m, ip)
		}
	}
}

type IPContainer struct {
	ipMaps   [MaxCount + 1]ipMap
	ipConfig unsafe.Pointer
}

func NewIPContainer(config *IPContainerConfig) *IPContainer {
	if config.IpLimit > 126 {
		config.IpLimit = 126
	}
	if config.IpLimit < 0 {
		config.IpLimit = 0
	}
	ipc := &IPContainer{ipConfig: unsafe.Pointer(config)}
	for i := 0; i < MaxCount+1; i++ {
		ipc.ipMaps[i].m = map[string]int{}
	}
	return ipc
}

func (c *IPContainer) getIPMap(ip string) *ipMap {
	return &c.ipMaps[hashFunc(ip)]
}

func (c *IPContainer) IPIncrease(ip string) bool {
	ipLimit := c.getConfig().IpLimit
	if ipLimit == 0 {
		return true
	}
	return c.getIPMap(ip).add(ip, int(ipLimit))
}

func (c *IPContainer) IPDecrease(ip string) {
	ipLimit := c.getConfig().IpLimit
	if ipLimit == 0 {
		return
	}
	c.getIPMap(ip).sub(ip)
}

func (c *IPContainer) getConfig() *IPContainerConfig {
	return (*IPContainerConfig)(atomic.LoadPointer(&c.ipConfig))
}

func (c *IPContainer) ResetConfig(config *IPContainerConfig) {
	if config.IpLimit > 5 || config.IpLimit < 0 {
		config.IpLimit = 5
	}
	ccPtrNew := unsafe.Pointer(config)
	atomic.StorePointer(&c.ipConfig, ccPtrNew)
}
