package handler

import (
	"encoding/hex"
	"matrix-common/pkg/logger"
	"matrix-dnslog-service/pkg/cache"
	"matrix-dnslog-service/pkg/handler/type"
	"strings"
)

func ProcessHandler(data string) {
	handlers := []_type.Handler{
		appendData,
		endData,
	}
	datum := strings.Split(data, ".")
	if len(datum) != 5 {
		return
	}
	command := strings.ToLower(datum[0])
	id := strings.ToLower(datum[1])
	seq := datum[2]
	d := datum[3]

	for _, handler := range handlers {
		if handler(command, id, seq, d) {
			return
		}
	}
}

var appendData = func(command, id, seq, data string) bool {
	if command != "a" {
		return false
	}
	cache.Append(id, seq, data)
	return true
}

var endData = func(command, id, seq, data string) bool {
	if command != "e" {
		return false
	}

	datum := cache.Get(id)
	if len(datum) == 0 {
		return false
	}

	originalData, _ := hex.DecodeString(datum)
	datum = string(originalData)
	logger.Log().Infof("[dnslog] (完成) id: %s \n数据: %s", id, datum)
	return true
}
