package album

import (
	"log"

	"git.trj.tw/golang/go-gallery/modules/context"
	"git.trj.tw/golang/go-gallery/modules/utils"

	"git.trj.tw/golang/go-gallery/models"
)

// GetAllAlbums -
func GetAllAlbums(c *context.Context) {
	val, ok := c.Get("token")

	if !ok {
		c.CustomRes("Foridden", "User token data not found")
	}

	albums, err := models.GetUserAlbums(val.(map[string]interface{})["user"].(map[string]interface{})["id"].(string))
	log.Println(err)
	if err != nil {
		c.ServerError(nil)
		return
	}

	data := make(map[string]interface{})
	data["albums"] = make([]map[string]interface{}, 0)
	for _, v := range albums {
		log.Println(v)
		data["albums"] = append(data["albums"].([]map[string]interface{}), utils.ToMap(v))
	}
	c.Success(data)
}

// GetAlbum -
func GetAlbum(c *context.Context) {
	id := c.Param("id")
	val, ok := c.Get("token")
	if !ok {
		c.CustomRes("Foridden", "user token data not found")
		return
	}
	uid := val.(map[string]interface{})["user"].(map[string]interface{})["id"].(string)

	album, err := models.GetAlbum(id, uid)
	if err != nil {
		c.ServerError(nil)
		return
	}
	if album == nil {
		c.NotFound("album not found")
		return
	}

	data := make(map[string]interface{})
	data["album"] = album
	c.Success(data)
}

// CreateAlbum -
func CreateAlbum(c *context.Context) {
	postData := struct {
		Name   string `json:"name" binding:"required"`
		Public bool   `json:"public" binding:"exists"`
	}{
		Public: false,
	}
	token, ok := c.Get("token")
	if !ok {
		c.CustomRes("Foridden", "user token data not found")
		return
	}
	uid, ok := token.(map[string]interface{})["user"].(map[string]interface{})["id"].(string)

	err := c.BindJSON(&postData)
	if err != nil {
		c.DataFormat(nil)
		return
	}

	album := &models.Album{
		UID:    uid,
		Name:   postData.Name,
		Public: postData.Public,
	}

	err = album.Create()
	if err != nil {
		c.ServerError(nil)
		return
	}

	res := utils.ToMap(album)
	m := make(map[string]interface{})
	m["album"] = res
	c.Success(m)
}

// UpdateAlbum -
func UpdateAlbum(c *context.Context) {
	id := c.Param("id")
	postData := struct {
		Name   string `json:"name" binding:"required"`
		Public bool   `json:"public" binding:"required"`
	}{}
	if len(id) == 0 {
		c.NotFound(nil)
		return
	}
	token, ok := c.Get("token")
	if !ok {
		c.CustomRes("Foridden", "user token data not found")
		return
	}
	uid, ok := token.(map[string]interface{})["user"].(map[string]interface{})["id"].(string)
	err := c.BindData(&postData)
	if err != nil {
		c.DataFormat(nil)
		return
	}

	album, err := models.GetAlbum(id, uid)
	if err != nil {
		c.ServerError(nil)
		return
	}
	if album == nil {
		c.NotFound("album not found")
		return
	}

	album.Name = postData.Name
	album.Public = postData.Public
	err = album.Update()
	if err != nil {
		c.ServerError(nil)
		return
	}

	res := utils.ToMap(album)
	m := make(map[string]interface{})
	m["album"] = res
	c.Success(m)
}
