package main

import (
	"crypto/md5"
	"fmt"
	"io"
	"net"
	"sync/atomic"
	"time"

	"./log"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

const (
	NAME         = "gate"
	VERSION      = "0.0.1"
	CONF_PATH    = "./proxy_gate.json"
	SYS_BUF_SIZE = 1024 * 2
)

var (
	defaultWorkPool   = newWorkPool(10000)
	Md5NotEqual       int32
	validateFailCount int32
	acceptBlockCount  int32
	onlineCount       int32
	warnLog           = log.NewLogger(true, "./head_packet_validate", zapcore.DebugLevel)
	WarnChan          = make(chan func(), 10000)
	g_http_address    = ""
)

func init() {
	go func() {
		for {
			time.Sleep(time.Second)
			fmt.Println(atomic.LoadInt32(&Md5NotEqual), atomic.LoadInt32(&validateFailCount), atomic.LoadInt32(&acceptBlockCount), atomic.LoadInt32(&onlineCount))
		}
	}()
	go WarnLog()
}

func PutWarnLog(f func()) {
	if len(WarnChan) < 9000 {
		WarnChan <- f
	}
}

func WarnLog() {
	for f := range WarnChan {
		f()
	}
}

func MD5(src string) (string, error) {
	h := md5.New()
	_, err := io.WriteString(h, src)
	if err != nil {
		return "", err
	}
	cipherStr := h.Sum(nil)
	return fmt.Sprintf("%x", cipherStr), nil
}

func ListenTest(addr string) bool {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		log.Error("test listen failed", zap.String("addr", addr), zap.Error(err))
		return false
	}
	ln.Close()
	return true
}
