package main

import (
	"fmt"
	"github.com/flamego/captcha"
	"github.com/flamego/flamego"
	"github.com/flamego/session"
	"github.com/flamego/template"
	"github.com/rs/zerolog/log"
	"image"
	"net/http"
	"time"
)

type Gallery struct {
	Id int64 `db:"id"`
	OwnerId int64 `db:"owner_id"`
	Name string `db:"name"`
	MainImage string `db:"mainImage"`
	MainImageOriginal string `db:"mainImageOriginal"`
	GroupID *int64 `db:"group_id"`

}

func galleryNewForm(t template.Template, data template.Data, s session.Session, captcha captcha.Captcha, c flamego.Context) {
	if s.Get("user_id") == nil {
		c.Redirect("/login", http.StatusTemporaryRedirect)
		return
	}
	t.HTML(http.StatusOK, "gallery_new")
}

func galleryNew(t template.Template, data template.Data, s session.Session, c flamego.Context) string {
	log.Debug().Msg("New Gallery")
	c.Request().ParseMultipartForm(9001)
	tx := sqlConnection.MustBegin()
	//Create Gallery
	res, err := tx.NamedExec(`INSERT INTO gallery (owner_id,name) VALUES (:owner,:name)`,
		map[string]interface{}{
			"owner": s.Get("user_id"),
			"name": c.Request().FormValue("name"),
		})
	if err != nil {
		panic(err)
	}

	galleryId, err := res.LastInsertId()
	if err != nil {
		panic(err)
	}

	//Upload Croped Image
	file, _, err  := c.Request().FormFile("cropImage")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	cropedImage, _ , err := image.Decode(file)
	if err != nil {
		panic(err)
	}
	path := fmt.Sprintf("/gallery/%v/%v/main/%v-%v", s.Get("user_id"), galleryId, time.Now().UnixNano(), "crop.png")
	uploadImageToS3(cropedImage, path)

	//Upload Original Image

	fileOrginal, fileHeaderOrginal, err  := c.Request().FormFile("orginal")
	if err != nil {
		panic(err)
	}
	defer fileOrginal.Close()

	orignalImage, _ , err := image.Decode(fileOrginal)
	if err != nil {
		panic(err)
	}
	pathOrignal := fmt.Sprintf("/gallery/%v/%v/main/%v-orginal-%v", s.Get("user_id"), galleryId, time.Now().UnixNano(), fileHeaderOrginal.Filename)
	uploadImageToS3(orignalImage, pathOrignal)

	//Update sql data


	_, err = tx.NamedExec(`UPDATE gallery SET mainImage = :uploadPath, mainImageOriginal = :uploadPathOriginal WHERE id = :id`,
		map[string]interface{}{
			"uploadPath": path,
			"uploadPathOriginal": pathOrignal,
			"id":         galleryId,
		})
	if err != nil {
		panic(err)
	}

	err = tx.Commit()
	if err != nil {
		panic(err)
	}

	return fmt.Sprintf("{\"id\": %d}", galleryId)

}

func galleryEdit(t template.Template)  {
	t.HTML(http.StatusOK, "gallery_edit")
}