package main

import (
	"fmt"
	"encoding/json"
	"net/http"
	"strings"
	"os"
	"context"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sns"
)

type App struct {
	requestData requestData
}

type requestData struct {
	method string
	protocol string
	content_length int64
	transfer_encoding []string
	remote_address string
	remote_port string
	request_uri string
	//tls_metadata http.tls.ConnectionState
	headers http.Header
	//body string
	body []byte
	//form_data http.url.Values
	url string
}

type SMS struct {
	Message string `json:"message"`
	DestNo string `json:"to"`
}

func sendResponse(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	w.WriteHeader(http.StatusServiceUnavailable)

	//fmt.Fprintln(w, "Hello World!")
}

func sendResponse2(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	w.WriteHeader(http.StatusOK)

	//fmt.Fprintln(w, "Hello World!")
}

func sendResponse3(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	w.WriteHeader(http.StatusInternalServerError)

	//fmt.Fprintln(w, "Hello World!")
}

func checkIP(reqData *requestData, w http.ResponseWriter) int {
	var whitelisted_ip []string

	whitelisted_ip = append(whitelisted_ip, "105.233.34.134")
	whitelisted_ip = append(whitelisted_ip, "156.38.200.7")

	for _,ip:= range whitelisted_ip {
		if ip == reqData.remote_address {
			fmt.Println("Match found! ", reqData.remote_address)
			sendResponse2(w)

			return 0
		}
	}

	sendResponse(w)

	return 1
}

func sendSMS(reqData *requestData, sms_deets *SMS, w http.ResponseWriter) int {
	//err := json.Unmarshal(reqData.body, &sms_deets)
	//if err != nil {
		//sendResponse3(w)

	//	return 1
	//}

	err := os.Setenv("AWS_ACCESS_KEY", "AKIARTV6SB2DHXEZW553")
	if err != nil {
		// log error
		sendResponse3(w)
	}

	err = os.Setenv("AWS_SECRET_ACCESS_KEY", "h7KFrorkmPY1jWwO2foOi24aRHEYFS0XxQIjituv")
	if err != nil {
		// log error
		sendResponse3(w)
	}

	err = os.Setenv("AWS_REGION", "eu-north-1")
	if err != nil {
		// log error
		sendResponse3(w)
	}

	cfg, err2 := config.LoadDefaultConfig(context.TODO(), config.WithRegion("eu-north-1"))
	if err2 != nil {
		fmt.Println("CONFIG ERROR!!!")
	}

	client := sns.NewFromConfig(cfg)

	input := &sns.PublishInput {
		Message: aws.String(sms_deets.Message),
		PhoneNumber: aws.String(sms_deets.DestNo),
	}

	result, err3 := client.Publish(context.TODO(), input)
	if err3 != nil {
		fmt.Println("ASDAD")
	} else {
		fmt.Println(*result.MessageId)
	}

	

	fmt.Println("\n")
	fmt.Println("Form Data")
	fmt.Println("=========")
	fmt.Println("Json Message: ", sms_deets.Message)
	fmt.Println("Json DestNo: ", sms_deets.DestNo)
	fmt.Println("\n")

	// Decode the incoming json request
	/*decoder := json.NewDecoder(r.Body)
	_ = decoder
	err := decoder.Decode(&sms_deets)
	if err != nil {
		fmt.Println("ERROR!")
	}
	defer r.Body.Close()*/

	os.Unsetenv("AWS_ACCESS_KEY")
	os.Unsetenv("AWS_SECRET_ACCESS_KEY")
	os.Unsetenv("AWS_REGION")

	return 0
}

func getPostData(w http.ResponseWriter, r *http.Request) {

	// add logging

	meh := strings.Split(r.RemoteAddr, ":")
	ip := meh[0]
	port := meh[1]

	reqData := &requestData {
		method: r.Method,
		protocol: r.Proto,
		content_length: r.ContentLength,
		transfer_encoding: r.TransferEncoding,
		remote_address: ip,
		remote_port: port,
		request_uri: r.RequestURI,
		//tls_metadata: r.TLS,
		headers: r.Header,
		body: nil,
		url: r.URL.String(),
		//r.postForm: r.PostForm,
	}
	
	// Check if the source ip is whitelisted
	e := checkIP(reqData, w)
	if e > 0 {
		return
	}
	
	sms_deets := new (SMS)

	// Decode the incoming json request
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&sms_deets)
	if err != nil {
		// Log this error fmt.Println("ERROR!")
		sendResponse3(w)
	}
	defer r.Body.Close()
	
	sendSMS(reqData, sms_deets, w)
}

func main () {
	http.HandleFunc("/send_sms", getPostData)
	
	fmt.Println("Starting HTTPS Server...")
	
	http.ListenAndServeTLS(":8443", "/etc/letsencrypt/live/prd-jhb-ep01.cm-ha.co.za/fullchain.pem", "/etc/letsencrypt/live/prd-jhb-ep01.cm-ha.co.za/privkey.pem", nil)
}

