package main

import (
	"fmt"
	"log"
	"net/http"
	"regexp"
	"strings"
)

// tracker handler

func save_tracker_settingsHandler(response http.ResponseWriter, request *http.Request) {
	name := getUserName(request)
	if name != "" {

		deveui, ok := request.URL.Query()["deveui"]

		if !ok || len(deveui[0]) < 1 {
			log.Println("Url Param 'deveui' is missing")
			fmt.Fprintf(response, "{ \"rc\": 1, \"msg\": \"deveui must be specified in URL\" }")
			return
		}
		// Query()["deveui"] will return an array of items,
		// we only want the single item.
		mydeveui := deveui[0]

		if len(mydeveui) != 16 {
			log.Println("specified 'deveui' has invalid length")
			fmt.Fprintf(response, "{ \"rc\": 8, \"msg\": \"specified deveui has invalid length\" }")
			return
		}

		if !(Contains(getMyDevs(name), mydeveui)) {
			log.Println("specified 'deveui' does not belong to this user")
			fmt.Fprintf(response, "{ \"rc\": 2, \"msg\": \"specified deveui does not belong to this user\" }")
			return
		}

		log.Println("Url Param 'deveui' is: " + string(mydeveui))

		alias, ok2 := request.URL.Query()["alias"]

		if !ok2 || len(alias[0]) < 1 {
			log.Println("Url Param 'alias' is missing")
			fmt.Fprintf(response, "{ \"rc\": 3, \"msg\": \"alias must be specified in URL\" }")
			return
		}
		myalias := alias[0]

		// validate alias
		match, _ := regexp.MatchString("^[a-zA-Z0-9 ]{1,25}$", myalias)
		if !(match) {
			log.Println("Url Param 'alias' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 9, \"msg\": \"alias is not valid\" }")
			return
		}

		smsalarmactive, ok3 := request.URL.Query()["smsalarmactive"]

		if !ok3 || len(smsalarmactive[0]) < 1 {
			log.Println("Url Param 'smsalarmactive' is missing")
			fmt.Fprintf(response, "{ \"rc\": 4, \"msg\": \"smsalarmactive must be specified in URL\" }")
			return
		}
		mysmsalarmactive := smsalarmactive[0]

		if !((mysmsalarmactive == "0") || (mysmsalarmactive == "1")) {
			log.Println("Url Param 'smsalarmactive' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 10, \"msg\": \"smsalarmactive is not valid\" }")
			return
		}

		smsnumber, ok4 := request.URL.Query()["smsnumber"]

		if !ok4 || len(smsnumber[0]) < 1 {
			log.Println("Url Param 'smsnumber' is missing")
			fmt.Fprintf(response, "{ \"rc\": 5, \"msg\": \"smsnumber must be specified in URL\" }")
			return
		}
		mysmsnumber := smsnumber[0]

		match1, _ := regexp.MatchString(`^\+[0-9]{11,11}$`, mysmsnumber)
		if !(match1) {
			log.Println("Url Param 'smsnumber' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 11, \"msg\": \"smsnumber is not valid, must be in in format +41791234567\" }")
			return
		}

		emailalarmactive, ok5 := request.URL.Query()["emailalarmactive"]

		if !ok5 || len(emailalarmactive[0]) < 1 {
			log.Println("Url Param 'emailalarmactive' is missing")
			fmt.Fprintf(response, "{ \"rc\": 12, \"msg\": \"emailalarmactive must be specified in URL\" }")
			return
		}
		myemailalarmactive := emailalarmactive[0]

		if !((myemailalarmactive == "0") || (myemailalarmactive == "1")) {
			log.Println("Url Param 'emailalarmactive' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 13, \"msg\": \"emailalarmactive is not valid\" }")
			return
		}

		email, ok6 := request.URL.Query()["email"]

		if !ok6 {
			log.Println("Url Param 'email' is missing")
			fmt.Fprintf(response, "{ \"rc\": 14, \"msg\": \"email must be specified in URL\" }")
			return
		}
		myemail := email[0]

		match2, _ := regexp.MatchString(`^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([,.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$`, myemail)
		if !(match2) {
			log.Println("Url Param 'email' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 15, \"msg\": \"email is not valid, must be in in format max.mustermann@example.com\" }")
			return
		}

		greenzone, ok7 := request.URL.Query()["greenzone"]

		if !ok7 {
			log.Println("Url Param 'greenzone' is missing")
			fmt.Fprintf(response, "{ \"rc\": 16, \"msg\": \"greenzone must be specified in URL\" }")
			return
		}
		mygreenzone := strings.ReplaceAll(greenzone[0], " ", "")

		match3, _ := regexp.MatchString(`^$|^[0-9]+\.[0-9]+,[0-9]+\.[0-9]+,[0-9]+\.[0-9]+,[0-9]+\.[0-9]+$`, mygreenzone)
		if !(match3) {
			log.Println("Url Param 'greenzone' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 17, \"msg\": \"greenzone is not valid, must be in in 123.45,123.45,123.45,123.45\" }")
			return
		}

		var mydev Dev
		mydev.Deveui = mydeveui
		mydev.Alias = myalias
		mydev.SmsAlarmactive = mysmsalarmactive
		mydev.Smsnumber = mysmsnumber
		mydev.EmailAlarmactive = myemailalarmactive
		mydev.Email = myemail
		mydev.Greenzone = mygreenzone

		// now we try to save the settings
		err := updateTrackerSettings(mydev)

		if err != nil {
			log.Println("Error to Update Device Settings")
			fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"error with saving device settings\" }")
			return
		} else {
			fmt.Fprintf(response, "{ \"rc\": 0, \"msg\": \"SUCCESS\" }")
		}

	} else {
		fmt.Fprintf(response, "{ \"rc\": 7, \"msg\": \"Only available for logged in users\" }")
	}
}

func save_tracker_greenzoneHandler(response http.ResponseWriter, request *http.Request) {
	name := getUserName(request)
	if name != "" {

		deveui, ok := request.URL.Query()["deveui"]

		if !ok || len(deveui[0]) < 1 {
			log.Println("Url Param 'deveui' is missing")
			fmt.Fprintf(response, "{ \"rc\": 1, \"msg\": \"deveui must be specified in URL\" }")
			return
		}
		// Query()["deveui"] will return an array of items,
		// we only want the single item.
		mydeveui := deveui[0]

		if len(mydeveui) != 16 {
			log.Println("specified 'deveui' has invalid length")
			fmt.Fprintf(response, "{ \"rc\": 8, \"msg\": \"specified deveui has invalid length\" }")
			return
		}

		if !(Contains(getMyDevs(name), mydeveui)) {
			log.Println("specified 'deveui' does not belong to this user")
			fmt.Fprintf(response, "{ \"rc\": 2, \"msg\": \"specified deveui does not belong to this user\" }")
			return
		}

		log.Println("Url Param 'deveui' is: " + string(mydeveui))

		greenzone, ok1 := request.URL.Query()["greenzone"]

		if !ok1 {
			log.Println("Url Param 'greenzone' is missing")
			fmt.Fprintf(response, "{ \"rc\": 3, \"msg\": \"greenzone must be specified in URL\" }")
			return
		}
		mygreenzone := greenzone[0]

		match, _ := regexp.MatchString(`^$|^[0-9]+\.[0-9]+,[0-9]+\.[0-9]+,[0-9]+\.[0-9]+,[0-9]+\.[0-9]+$`, mygreenzone)
		if !(match) {
			log.Println("Url Param 'greenzone' is not valid")
			fmt.Fprintf(response, "{ \"rc\": 17, \"msg\": \"greenzone is not valid, must be in in 123.45,123.45,123.45,123.45\" }")
			return
		}

		// now we try to save the settings
		err := updateTrackerGreenzone(mydeveui, mygreenzone)

		if err != nil {
			log.Println("Error to Update Greenzone")
			fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"error with updating greenzone\" }")
			return
		} else {
			fmt.Fprintf(response, "{ \"rc\": 0, \"msg\": \"SUCCESS\" }")
		}

	} else {
		fmt.Fprintf(response, "{ \"rc\": 7, \"msg\": \"Only available for logged in users\" }")
	}
}
