package imap

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

const (
	PRE_COMPARE_STR  = "* OK"
	SEND_COMPARE_STR = "* BYE"
)

type IMAPMatcher struct {
	sendPackets []*packet.Packet
}

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

	switch index {
	case 0:

		recvStr := string(packet.Buffer)

		if len(recvStr) < 3 {
			return false
		}

		compareStr := recvStr[0:4]

		if compareStr == PRE_COMPARE_STR {
			return true
		}

	case 1:

		recvStr := string(packet.Buffer)

		if len(recvStr) < 5 {
			return false
		}

		compareStr := recvStr[0:5]

		if compareStr == SEND_COMPARE_STR {
			return true
		}

	}

	return false
}

func (i *IMAPMatcher) PacketCount() int {
	return len(i.sendPackets)
}
func (i *IMAPMatcher) Packet(index int) *packet.Packet {
	return i.sendPackets[index]
}
func (i *IMAPMatcher) ServiceName() string {
	return "IMAP"
}

func (i *IMAPMatcher) IsError(index int, packet *packet.Packet, info *types.ServiceScanInfo) bool {
	return false
}
func (i *IMAPMatcher) IsNoResponse(index int) bool {

	return false
}

func (i *IMAPMatcher) IsPrePacket() bool {
	return true
}

func NewIMAPMatcher() *IMAPMatcher {

	im := IMAPMatcher{}

	reqStr := "A0001 LOGOUT\r\n"
	byte := make([]byte, len(reqStr))
	copy(byte[:], reqStr)

	im.sendPackets = append(im.sendPackets, packet.NewPacket(byte, len(reqStr)))

	return &im

}
