package main

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
)

func sendEmailAccu(username string, alias string, deveui string, accu_percent string, threshold int, level string) {
	fmt.Printf("SEND EMAIL ACCU (%s) - %s:%s\n", level, username, deveui)
	mail_message := "To: " + username + `
From: info@wo-bisch.ch
Subject: ` + level + ` - wo-bisch.ch: Akku Ladezustand (` + alias + `)

Lieber Benutzer von wo-bisch.ch

Der Akku von "` + alias + `" (DevEUI: ` + deveui + `) ist noch zu ` + accu_percent + ` Prozent geladen.

Bitte rechtzeitig wieder laden! Bei Unterschreitung von 5% Ladung erscheint die letzte Warnung.

Mit freundlichen Grüssen
--
wo-bisch.ch`

	sendEmail(username, "mail@wo-bisch.ch", mail_message)
}

func sendEmailAbo(username string, alias string, deveui string, days_left int, level string) {
	var ablauftext string
	if days_left == 0 {
		fmt.Printf("SEND EMAIL ABO (%s) - %s:%s\n", level, username, deveui)
		ablauftext = "Das Abo von \"" + alias + "\" (DevEUI: " + deveui + ") laeuft heute ab."
	} else if days_left > 0 {
		fmt.Printf("SEND EMAIL ABO (%s) - %s:%s\n", level, username, deveui)
		ablauftext = "Das Abo von \"" + alias + "\" (DevEUI: " + deveui + ") laeuft in " + strconv.Itoa(days_left) + " Tagen ab."
	}
	mail_message := "To: " + username + `
From: info@wo-bisch.ch
Subject: ` + level + ` - wo-bisch.ch: Abo verlaengern (` + alias + `)

Lieber Benutzer von wo-bisch.ch

` + ablauftext + `

Bitte Abo verlaengern auf https://wo-bisch.ch

Mit freundlichen Grüssen
--
wo-bisch.ch`

	sendEmail(username, "mail@wo-bisch.ch", mail_message)
}

func CheckThreshold(d string, vp int, u2 string, last_metric OneMetric, info_threshold int, warning_threshold int, alert_threshold int) bool {
	var alias string
	if vp <= info_threshold {
		alias = getDevAlias(d)
	}
	if vp <= alert_threshold {
		if AlarmNotAlreadySent("alarm_sent_accu:", d, u2, alert_threshold) {
			sendEmailAccu(u2, alias, d, last_metric.BatteryPercent, alert_threshold, "ALARM")
			InsertAlert("alarm_sent_accu:", d, u2, alert_threshold)
		}
		return false
	}
	if vp <= warning_threshold {
		if AlarmNotAlreadySent("alarm_sent_accu:", d, u2, warning_threshold) {
			sendEmailAccu(u2, alias, d, last_metric.BatteryPercent, warning_threshold, "WARNING")
			InsertAlert("alarm_sent_accu:", d, u2, warning_threshold)
		}
		return false
	}
	if vp <= info_threshold {
		if AlarmNotAlreadySent("alarm_sent_accu:", d, u2, info_threshold) {
			sendEmailAccu(u2, alias, d, last_metric.BatteryPercent, alert_threshold, "INFO")
			InsertAlert("alarm_sent_accu:", d, u2, info_threshold)
		}
		return false
	}
	return true
}

func sendReminder(days int) bool {
	return (days == 0 || days == 5 || days == 10)
}

func checkNodes() {
	logit("Starting check_battery...")

	users := getUsers()
	for _, u := range users {
		//fmt.Println(u)
		u2 := u[5:]
		my_devs := getMyDevs(u2)
		for _, d := range my_devs {
			fmt.Printf("%s:%s\n", u2, d)
			if !strings.HasPrefix(d, "@") {
				last_metric := getLastMetrics(d)
				// Zuerst der Batteriealarm
				if last_metric.BatteryPercent != "" {
					fmt.Printf("%s:%s:%s Percent:%s:%d\n", u2, d, last_metric.BatteryPercent, last_metric.ActiveUntil, last_metric.DaysUntilDeactivated)
					vp, _ := strconv.Atoi(last_metric.BatteryPercent)
					if CheckThreshold(d, vp, u2, last_metric, 20, 10, 5) {
						DeleteAlert("alarm_sent_accu:", d, u2)
					}
				}
				// Jetzt der Alarm wegen der Abodauer
				if sendReminder(last_metric.DaysUntilDeactivated) {
					fmt.Printf("SEND EMAIL %s:%s:%s Percent:%s:%d\n", u2, d, last_metric.BatteryPercent, last_metric.ActiveUntil, last_metric.DaysUntilDeactivated)
					alias := getDevAlias(d)
					sendEmailAbo(u2, alias, d, last_metric.DaysUntilDeactivated, "INFO")
				}
			}
		}
	}
	logit("Done with check_battery...")
}

func checkNodesHandler(w http.ResponseWriter, req *http.Request) {
	headers := req.Header

	val, ok := headers["X-Checknodes"]
	if ok {
		fmt.Printf("X-Checknodes header is present with value %s\n", val)
		checkNodes()
	} else {
		fmt.Println("X-Checknodes header is not present")
	}
	w.WriteHeader(http.StatusOK)
}
