package main

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

	//"./utils"

	"github.com/yosssi/gmq/mqtt"
	"github.com/yosssi/gmq/mqtt/client"
)

func main() {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill)

	incoming_updates_chan := IncomingMQTTProcessor(1*time.Second, cli, db, loggers)

	err = cli.Subscribe(&client.SubscribeOptions{
		SubReqs: []*client.SubReq{
			&client.SubReq{
				TopicFilter: []byte("publish_out/#"),
				QoS:         mqtt.QoS0,
				Handler: func(topicName, message []byte) {
					msgStr := string(message)
					t := strings.Split(string(topicName), "/")
					hostname := t[1]

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

						for _, reading := range readings {
							if reading.Type == "Gateway" {
								continue
							}
							incoming := Incoming_json{
								Hostname:         hostname,
								MAC:              reading.MAC,
								RSSI:             int64(reading.RSSI),
								Data:             reading.RawData,
								HB_ButtonCounter: parseButtonState(reading.RawData),
							}
							incoming_updates_chan <- incoming
						}
					} 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 := 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)
							}
							incoming_updates_chan <- incoming
						}
					}
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Println("CONNECTED TO MQTT")
	fmt.Println("\n ")
	fmt.Println("Visit http://" + *http_host_path_ptr + " on your browser to see the web interface")
	fmt.Println("\n ")

	go startServer()

	// Wait for receiving a signal.
	<-sigc

	// Disconnect the Network Connection.
	if err := cli.Disconnect(); err != nil {
		panic(err)
	}
}
