package main

import (
	"fmt"
	"io/ioutil"
	"log"
	mu "mfw/util"
	"net"
	"net/http"
	"sync"
	"time"
)

var udptaskmap = &sync.Map{}
var tomail string
var api string

type udpNode struct {
	data      []byte
	addr      *net.UDPAddr
	timestamp int64
	retry     int
}

func checkMapJob() {
	//阿里云内网无法发送邮件
	jkmail, _ := sysconfig["jkmail"].(map[string]interface{})
	if jkmail != nil {
		tomail, _ = jkmail["to"].(string)
		api, _ = jkmail["api"].(string)
	}
	log.Println("start checkMapJob", tomail, sysconfig["jkmail"])
	for {
		udptaskmap.Range(func(k, v interface{}) bool {
			now := time.Now().Unix()
			node, _ := v.(*udpNode)
			if now-node.timestamp > 120 {
				node.retry++
				if node.retry > 5 {
					log.Println("udp重试失败", k)
					udptaskmap.Delete(k)
					res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", api, tomail, "pingfen-send-fail", k.(string)))
					if err == nil {
						defer res.Body.Close()
						read, err := ioutil.ReadAll(res.Body)
						log.Println("邮件发发送：", string(read), err)
					}
				} else {
					log.Println("udp重发", k)
					udpclient.WriteUdp(node.data, mu.OP_TYPE_DATA, node.addr)
				}
			} else if now-node.timestamp > 10 {
				log.Println("udp任务超时中..", k)
			}
			return true
		})
		time.Sleep(60 * time.Second)
	}
}
