package redis

import (
	"git.loafle.net/overflow/overflow_probe/discovery/core/scan/service/matcher/packet"
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types"
	"strings"
)

const REDIS_PING string = "*1\r\n$4\r\nping\r\n"

type RedisMatcher struct {
	packets []*packet.Packet
}

func NewRedisMatcher() *RedisMatcher {

	redisMatcher := &RedisMatcher{}

	redisMatcher.packets = append(redisMatcher.packets, packet.NewPacket([]byte(REDIS_PING), len(REDIS_PING)))

	return redisMatcher
}

func (t *RedisMatcher) ServiceName() string {
	return "Redis"
}

func (t *RedisMatcher) PacketCount() int {
	return len(t.packets)
}
func (t *RedisMatcher) Packet(index int) *packet.Packet {
	return t.packets[index]
}

func (t *RedisMatcher) IsError(index int, packet *packet.Packet, info *types.ServiceScanInfo) bool {
	return false
}

func (t *RedisMatcher) IsNoResponse(index int) bool {
	return false
}

func (t *RedisMatcher) IsPrePacket() bool {
	return false
}

func (t *RedisMatcher) Match(index int, packet *packet.Packet, info *types.ServiceScanInfo) bool {

	if packet == nil {
		return false
	}

	resp := strings.Split(string(packet.Buffer), "\r\n")[0]
	if len(resp) <= 0 {
		return false
	}

	sign := string([]rune(resp)[0])
	if len(sign) <= 0 {
		return false
	}

	if sign == "+" {
		if resp == "+PONG" || resp == "+OK" {
			return true
		}
	}
	if sign == "-" {
		if resp == "-NOAUTH" || resp == "-ERR" {
			return true
		}
	}

	return false

}
