package http

import (
	"git.loafle.net/overflow/overflow_probe/matcher/packet"
	"git.loafle.net/overflow/overflow_probe/model/scaninfo"
	"strings"
)

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

func (h *HTTPMatcher) Match(index int, packet *packet.Packet, info scaninfo.ServiceScanInfo) bool {
	result := false

	if packet == nil || packet.Buffer == nil || packet.Len == 0 {
		return result
	}

	str := string(packet.Buffer)
	//fmt.Println(str)
	elems := strings.Split(str, "\r\n")

	if len(elems) <= 0 {
		return result
	}

	protocol := (elems[0])[:8]

	httpv0 := strings.Compare(protocol, "HTTP/1.0")
	httpv1 := strings.Compare(protocol, "HTTP/1.1")
	httpv2 := strings.Compare(protocol, "HTTP/1.2")

	if 0 == httpv0 || 0 == httpv1 || 0 == httpv2 {
		result = true
	}

	serverName := "Unknown Server"

	for _, valueStr := range elems {
		tempElems := strings.Split(valueStr, ":")

		if 0 == strings.Compare(tempElems[0], "Server") {
			serverName = tempElems[1]
			break
		}
	}

	strings.Compare(serverName, "Unknown")
	//fmt.Println("HTTP Server Name: ", serverName)

	return result
}

func (h *HTTPMatcher) PacketCount() int {
	return len(h.sendPackets)
}

func (h *HTTPMatcher) Packet(index int) *packet.Packet {

	return h.sendPackets[index]
}

func (h *HTTPMatcher) ServiceName() string {
	return "HTTP"
}

func (h *HTTPMatcher) IsError(index int, packet *packet.Packet, info scaninfo.ServiceScanInfo) bool {
	return false
}

func (h *HTTPMatcher) IsNoResponse(index int) bool {
	return false
}

func (h *HTTPMatcher) IsPrePacket() bool {
	return false
}

func NewHTTPMatcher() *HTTPMatcher {

	h := HTTPMatcher{}
	reqStr := "GET / HTTP/1.1\r\n\r\n"
	byte := make([]byte, len(reqStr))
	copy(byte[:], reqStr)

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

	return &h
}
