package src

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/chacha20poly1305"
)

const ivSize = 12
const DecryptedData = "DecryptedData"

func AEADHandler(c *gin.Context) {
	// get id
	uintID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		fmt.Printf("ERR %s", err.Error())
		c.AbortWithStatus(http.StatusUnauthorized)
	} else {
		// get key
		passcode, err := GetDeviceKey(uintID)
		if err != nil {
			fmt.Printf("ERR %s", err.Error())
			c.AbortWithStatus(http.StatusNotFound)
		} else {
			// get content
			data, err := c.GetRawData()
			if err != nil {
				fmt.Printf("ERR %s", err.Error())
				c.AbortWithStatus(http.StatusBadRequest)
			} else {
				// decrypt
				iv, ciphertext := data[:ivSize], data[ivSize:]
				aead, err := chacha20poly1305.New(passcode)
				if err != nil {
					fmt.Printf("ERR %s", err.Error())
					c.AbortWithStatus(http.StatusInternalServerError)
				} else {
					fmt.Printf("iv: %s cypher: %s", base64.StdEncoding.EncodeToString(iv), base64.StdEncoding.EncodeToString(ciphertext))
					plaintext, err := aead.Open(nil, iv, ciphertext, nil)

					if err != nil {
						fmt.Printf("ERR %s", err.Error())
						c.AbortWithStatus(http.StatusBadRequest)
					} else {
						c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(plaintext))
					}
				}
			}
		}
	}

}
