package util

import (
	"encoding/json"
	"errors"
	mu "mfw/util"
	qu "qfw/util"
	"time"
)

//
type DynamicIPMap struct {
	Code        string
	InvalidTime int64
}

var Msclient *mu.Client
var MsclientBid *mu.Client
var Alldownloader map[string]DynamicIPMap = make(map[string]DynamicIPMap)
var AlldownloaderBid map[string]DynamicIPMap = make(map[string]DynamicIPMap)

//
func processevent(p *mu.Packet) {
	defer mu.Catch()
	var data []byte
	switch p.Event {
	case mu.SERVICE_DOWNLOAD_APPEND_NODE:
		data = p.GetBusinessData()
		//log.Println("获取动态地址:", len(data), string(data))
		for i := 0; i < len(data)/8; i++ {
			code := string(data[i*8 : (i+1)*8])
			Alldownloader[code] = DynamicIPMap{
				Code:        code,
				InvalidTime: time.Now().Unix() + 60*10,
			}
		}
	case mu.SERVICE_DOWNLOAD_DELETE_NODE:
		data = p.GetBusinessData()
		//log.Println("删除动态地址:", len(data), string(data))
		for i := 0; i < len(data)/8; i++ {
			code := string(data[i*8 : (i+1)*8])
			delete(Alldownloader, code)
		}
	}
}
func processeventbid(p *mu.Packet) {
	defer mu.Catch()
	var data []byte
	switch p.Event {
	case mu.SERVICE_DOWNLOAD_APPEND_NODE:
		data = p.GetBusinessData()
		//log.Println("获取动态地址:", len(data), string(data))
		for i := 0; i < len(data)/8; i++ {
			code := string(data[i*8 : (i+1)*8])
			AlldownloaderBid[code] = DynamicIPMap{
				Code:        code,
				InvalidTime: time.Now().Unix() + 60*10,
			}
		}
	case mu.SERVICE_DOWNLOAD_DELETE_NODE:
		data = p.GetBusinessData()
		//log.Println("删除动态地址:", len(data), string(data))
		for i := 0; i < len(data)/8; i++ {
			code := string(data[i*8 : (i+1)*8])
			delete(AlldownloaderBid, code)
		}
	}
}

//
func gc4Alldownloader() {
	n := time.Now().Unix()
	for _, v := range Alldownloader {
		if v.InvalidTime < n {
			delete(Alldownloader, v.Code)
		}
	}
	time.AfterFunc(1*time.Minute, gc4Alldownloader)
}
func gc4AlldownloaderBid() {
	n := time.Now().Unix()
	for _, v := range AlldownloaderBid {
		if v.InvalidTime < n {
			delete(AlldownloaderBid, v.Code)
		}
	}
	time.AfterFunc(1*time.Minute, gc4AlldownloaderBid)
}

//初始化，启动消息客户端
func InitMsgClient(serveraddr, serveraddrbid, name, namebid string) {
	Msclient, _ = mu.NewClient(&mu.ClientConfig{ClientName: name,
		MsgServerAddr:   serveraddr,
		EventHandler:    processevent,
		CanHandleEvents: []int{mu.SERVICE_DOWNLOAD_APPEND_NODE, mu.SERVICE_DOWNLOAD_DELETE_NODE},
		ReadBufferSize:  10,
		WriteBufferSize: 10,
	})
	go gc4Alldownloader() //comm

	MsclientBid, _ = mu.NewClient(&mu.ClientConfig{ClientName: namebid,
		MsgServerAddr:   serveraddrbid,
		EventHandler:    processeventbid,
		CanHandleEvents: []int{mu.SERVICE_DOWNLOAD_APPEND_NODE, mu.SERVICE_DOWNLOAD_DELETE_NODE},
		ReadBufferSize:  10,
		WriteBufferSize: 10,
	})
	go gc4AlldownloaderBid() //bid
}

//爬虫上下架
func UpdateSpiderByCodeState(code, state string, event int) (bool, error) {
	msgid := mu.UUID(8)
	data := map[string]interface{}{
		"code":  code,
		"state": state,
	}
	rep := map[string]interface{}{}
	var bs []byte
	var err error
	if UploadEvents[event] == "bid" { //bid:803
		bs, err = MsclientBid.Call("", msgid, event, mu.SENDTO_TYPE_ALL_RECIVER, data, 60)
	} else { //comm:801
		bs, err = Msclient.Call("", msgid, event, mu.SENDTO_TYPE_ALL_RECIVER, data, 60)
	}
	if err != nil {
		return false, err
	} else {
		json.Unmarshal(bs, &rep)
		b, _ := rep["b"].(bool)
		if !b {
			err = errors.New(qu.ObjToString(rep["err"]))
		}
		return b, err
	}
}
