package api

import (
    "arimelody-web/log"
    "arimelody-web/model"
    "bufio"
    "encoding/base64"
    "errors"
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

func HandleImageUpload(app *model.AppState, data *string, directory string, filename string) (string, error) {
    split := strings.Split(*data, ";base64,")
    header := split[0]
    imageData, err := base64.StdEncoding.DecodeString(split[1])
    ext, _ := strings.CutPrefix(header, "data:image/")
    directory = filepath.Join(app.Config.DataDirectory, directory)

    switch ext {
    case "png":
    case "jpg":
    case "jpeg":
    default:
        return "", errors.New("Invalid image type. Allowed: .png, .jpg, .jpeg")
    }
    filename = fmt.Sprintf("%s.%s", filename, ext)

    // ensure directory exists
    os.MkdirAll(directory, os.ModePerm)

    imagePath := filepath.Join(directory, filename)
    file, err := os.Create(imagePath)
    if err != nil {
        return "", err
    }
    defer file.Close()

    // TODO: generate compressed versions of image (512x512?)

    buffer := bufio.NewWriter(file)
    _, err = buffer.Write(imageData)
    if err != nil {
        return "", nil
    }

    if err := buffer.Flush(); err != nil {
        return "", nil
    }

    app.Log.Info(log.TYPE_FILES, "\"%s/%s.%s\" created.", directory, filename, ext)

    return filename, nil
}
