package service

import (
	"git.loafle.net/overflow/overflow_probe/discovery/core/scan/service/matcher"
	"git.loafle.net/overflow/overflow_probe/discovery/core/scan/service/matcher/packet"
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types"
	log "github.com/cihub/seelog"
)

func processPostPacket(mats []matcher.Matcher, info *types.ServiceScanInfo, m ConnFactory) bool {

	var ser *types.DiscoveryService = nil
	var curMatcher matcher.Matcher = nil
	isFound := false

	for i := 0; i < len(mats); i++ {

		info.History = make([]*types.ServiceScanHistory, 0)
		conn, err := m.createSocket(info.Port.Host.Ip_, info.Port.Port_)
		if err != nil {
			log.Error(m.Type() + " process postpacket create socket error :" + info.Port.Host.Ip_ + " port: " + info.Port.Port_ + " error: " + err.Error())
			break
		}
		curMatcher = mats[i]

		for indexI := 0; indexI < curMatcher.PacketCount(); indexI++ {

			p := curMatcher.Packet(indexI)
			l, err := conn.Write(p.Buffer)
			if err != nil {
				break
			}
			if l != p.Len {
				break
			}
			AddServiceScanHistory(
				&info.History,
				types.NewServiceScanHistory(info.Port, curMatcher.ServiceName(), types.DIRECTION_SEND, p.Buffer))

			buf := make([]byte, 1024)
			l, err = conn.Read(buf)

			AddServiceScanHistory(
				&info.History,
				types.NewServiceScanHistory(info.Port, curMatcher.ServiceName(), types.DIRECTION_RECV, p.Buffer))

			if err != nil {
				if curMatcher.IsNoResponse(indexI) == true {
					ser = types.NewService(m.Type(), curMatcher.ServiceName(), info.Port)
					isFound = true
					break
				}
				break

			}

			if curMatcher.Match(indexI, packet.NewPacket(buf, l), info) == true {
				if indexI == (curMatcher.PacketCount() - 1) {
					ser = types.NewService(m.Type(), curMatcher.ServiceName(), info.Port)
					break
				}
				isFound = true
				continue
			} else {
				isFound = false
				break
			}

		}
		if isFound == true {
			conn.Close()
			break
		}
		conn.Close()
	}

	AddService(ser, info)
	if ser == nil {
		return false
	} else {
		return true
	}
}
