package modules

import (
	"errors"
	"fmt"
	"math"
)

func Cosine(a []float64, b []float64) (cosine float64, err error) {
	count := 0
	length_a := len(a)
	length_b := len(b)
	if length_a > length_b {
		count = length_a
	} else {
		count = length_b
	}
	sumA := 0.0
	s1 := 0.0
	s2 := 0.0
	for k := 0; k < count; k++ {
		if k >= length_a {
			s2 += math.Pow(b[k], 2)
			continue
		}
		if k >= length_b {
			s1 += math.Pow(a[k], 2)
			continue
		}
		sumA += a[k] * b[k]
		s1 += math.Pow(a[k], 2)
		s2 += math.Pow(b[k], 2)
	}
	if s1 == 0 || s2 == 0 {
		return 0.0, errors.New("Vectors should not be null (all zeros)")
	}
	return sumA / (math.Sqrt(s1) * math.Sqrt(s2)), nil
}

func (moscato *Moscato) ImageMatching(msg MsgUnit) {

	fmt.Println("gogoman")
	topic := msg.(PublishedImage).Topic
	sub_mng := moscato.SubscriptionManager

	// iplist for return
	//ipList := make([]string, 0)

	topicPtr := sub_mng.list
	ptr := topicPtr.getTopicBySimilarity(topic)

	// No topicNode
	if len(ptr) == 0 {
		fmt.Println("error")
		moscato.SendQueue <- myType{nil, msg, errors.New("No Exist Matching Topic")}
	} else {

		//find exact topic match
		fmt.Println("here1")
		valPtr := ptr[0]
		fmt.Println(valPtr.topic)
		iplist := make([]string, 0)
		for i := 0; i < topicPtr.size; i++ {
			pnt := sub_mng.subnum2conv[i]
			compare := ExactCompare(valPtr.topic, pnt)
			if compare == 1 {
				ipAddr := sub_mng.sub2ip[i]
				iplist = append(iplist, ipAddr)
			}
		}
		moscato.MatchingManager.match_count++
		moscato.SendQueue <- myType{iplist, msg, nil}
	}
}
