package mqtthandler

import (
	"fmt"
	"encoding/json"
	"strings"
	"log"
	"strconv"
	"os"
	"context"
	"time"

	"github.com/AFASystems/presence/internal/pkg/model"
	"github.com/segmentio/kafka-go"
)

func MqttHandler(writer *kafka.Writer, topicName []byte, message []byte) {
	hostname := strings.Split(string(topicName), "/")[1]
	msgStr := string(message)

	if strings.HasPrefix(msgStr, "[") {
		var readings []model.RawReading
		err := json.Unmarshal(message, &readings)
		if err != nil {
			log.Printf("Error parsing JSON: %v", err)
			return
		}

		for _, reading := range readings {
			if reading.Type == "Gateway" {
				continue
			}
			incoming := model.Incoming_json{
				Hostname:         hostname,
				MAC:              reading.MAC,
				RSSI:             int64(reading.RSSI),
				Data:             reading.RawData,
				HB_ButtonCounter: parseButtonState(reading.RawData),
			}

			encodedMsg, err := json.Marshal(incoming)
			if err != nil {
				fmt.Println("Error in marshaling: ", err)
			}

			msg := kafka.Message{
				Value: encodedMsg,
			}
			err = writer.WriteMessages(context.Background(), msg)
			if err != nil {
				fmt.Println("Error in writing to Kafka: ", err)
			}

			fmt.Println("message sent: ", time.Now())
		}
	} else {
		s := strings.Split(string(message), ",")
		if len(s) < 6 {
			log.Printf("Messaggio CSV non valido: %s", msgStr)
			return
		}

		rawdata := s[4]
		buttonCounter := parseButtonState(rawdata)
		if buttonCounter > 0 {
			incoming := model.Incoming_json{}
			i, _ := strconv.ParseInt(s[3], 10, 64)
			incoming.Hostname = hostname
			incoming.Beacon_type = "hb_button"
			incoming.MAC = s[1]
			incoming.RSSI = i
			incoming.Data = rawdata
			incoming.HB_ButtonCounter = buttonCounter

			read_line := strings.TrimRight(string(s[5]), "\r\n")
			it, err33 := strconv.Atoi(read_line)
			if err33 != nil {
				fmt.Println(it)
				fmt.Println(err33)
				os.Exit(2)
			}
		}
	}
}

func parseButtonState(raw string) int64 {
	raw = strings.ToUpper(raw)

	if strings.HasPrefix(raw, "0201060303E1FF12") && len(raw) >= 38 {
		buttonField := raw[34:38]
		if buttonValue, err := strconv.ParseInt(buttonField, 16, 64); err == nil {
			return buttonValue
		}
	}

	if strings.HasPrefix(raw, "02010612FF590") && len(raw) >= 24 {
		counterField := raw[22:24]
		buttonState, err := strconv.ParseInt(counterField, 16, 64)
		if err == nil {
			return buttonState
		}
	}

	return 0
}