package main

import (
	"bytes"
	"encoding/base64"
	"git.bbr-dev.info/brajkovic/resource_manager/resource"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

type LegacySave struct {
	Content    string `json:"content"`
	Path       string `json:"path"`
	Properties struct {
		Height    int    `json:"height"`
		Overwrite bool   `json:"overwrite"`
		MimeType  string `json:"mimeType"`
	} `json:"properties"`
}

func HandleLegacySave(resourceManager resource.Manager) gin.HandlerFunc {
	return func(c *gin.Context) {
		var legacySave LegacySave
		if err := c.ShouldBindJSON(&legacySave); err == nil {
			// removing image/(png/jpeg/...); start
			if strings.HasPrefix(legacySave.Content, "data:") {
				legacySave.Content = strings.Split(legacySave.Content, ";")[1]
			}
			if imageBytes, err := base64.StdEncoding.DecodeString(legacySave.Content); err == nil {
				if legacySave.Properties.Height > 0 {
					imageBytes, err = resizeImage(imageBytes, legacySave.Properties.Height)
				}
				mimeType := readMimeType(legacySave.Path, legacySave.Properties.MimeType)
				if err == nil {
					// request is sent to uplader service after which it is being uploaded
					resourceManager.Upload(resource.UploadRequest{
						Buffer:   bytes.NewBuffer(imageBytes),
						Path:     legacySave.Path,
						MimeType: mimeType,
					})
					// we return this as success
					c.Status(http.StatusNoContent)
				} else {
					c.AbortWithStatusJSON(400, gin.H{"error": "bad request"})
				}
			} else {
				c.AbortWithStatusJSON(400, gin.H{"error": "bad request"})
			}
		} else {
			c.AbortWithStatusJSON(400, gin.H{"error": "bad request"})
		}
	}
}

func HandleCopy(resourceManager resource.Manager) gin.HandlerFunc {
	return func(c *gin.Context) {
		from := c.Query("from")
		to := c.Query("to")
		overwrite := c.Query("overwrite") == "true"
		if err := resourceManager.Copy(from, to, overwrite); err != nil {
			log.Println(err)
			c.AbortWithStatus(500)
		} else {
			c.Status(201)
		}

	}
}

func HandlePresign(resourceManager resource.Manager) gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Query("path")
		url, err := resourceManager.Presign(c, path)
		if err != nil {
			c.AbortWithStatus(404)
			return
		}
		if c.Query("redirect") == "true" {
			c.Redirect(http.StatusTemporaryRedirect, url)
		} else {
			c.JSON(200, url)
		}
	}
}

func HandleGet(resourceManager resource.Manager) gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Query("path")
		data, err := resourceManager.Download(c, path)
		if err == nil {
			c.Data(200, readMimeType(path, ""), data)
		} else {
			c.AbortWithStatus(http.StatusNotFound)
		}
	}
}

func HandleDelete(resourceManager resource.Manager) gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Query("path")
		if err := resourceManager.Delete(path); err != nil {
			c.AbortWithError(400, err)
		} else {
			c.Status(204)
		}
	}
}
