package models

import (
	"database/sql"
	"errors"
	"time"

	"git.trj.tw/golang/utils/dbtool"
)

// Album model
type Album struct {
	ID     string    `sql:"id" cc:"id"`
	UID    string    `sql:"uid" cc:"uid"`
	Name   string    `sql:"name" cc:"name"`
	Public bool      `sql:"public" cc:"public"`
	Ctime  time.Time `sql:"ctime" cc:"ctime"`
	Mtime  time.Time `sql:"mtime" cc:"mtime"`
}

// GetAllAlbums -
func GetAllAlbums(arg ...bool) (album []Album, err error) {
	var rows *sql.Rows
	if len(arg) > 0 {
		rows, err = x.Query(`select "id", "uid", "name", "public", "ctime", "mtime" from "storage"."album" where "public" = $1`, arg[0])
	} else {
		rows, err = x.Query(`select "id", "uid", "name", "public", "ctime", "mtime" from "storage"."album"`)
	}

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	err = dbtool.ScanToStructAll(rows, &album)
	if err != nil {
		return nil, err
	}

	return
}

// GetUserAlbums -
func GetUserAlbums(uid string) (album []Album, err error) {
	if len(uid) == 0 {
		return nil, errors.New("user id empty")
	}
	rows, err := x.Query(`select "id", "uid", "name", "public", "ctime", "mtime" from "storage"."album" where "uid" = $1`, uid)

	err = dbtool.ScanToStructAll(rows, &album)
	if err != nil {
		return nil, err
	}
	return
}

// GetAlbum -
func GetAlbum(id, uid string) (album *Album, err error) {
	rows, err := x.Query(`selecy "id", "uid", "name", "public", "ctime", "mtime" where "id" = $1 and "uid" = $2 limit 1`, id, uid)
	if err != nil {
		return
	}
	defer rows.Close()
	ok, err := dbtool.ScanToStruct(rows, album)
	if err != nil {
		return
	}
	if !ok {
		return nil, nil
	}

	return
}

// Get -
func (a *Album) Get() (err error) {
	rows, err := x.Query(`select "id", "uid", "name", "public", "ctime", "mtime" from "storage"."album" where "id" = $1`, a.ID)
	if err != nil {
		return err
	}

	ok, err := dbtool.ScanToStruct(rows, a)
	if err != nil {
		return err
	}
	if !ok {
		return errors.New("album data not found")
	}
	return
}

// Create -
func (a *Album) Create() (err error) {
	if len(a.UID) == 0 || len(a.Name) == 0 {
		return errors.New("album data empty")
	}

	rows, err := x.Query(`insert into "storage"."album" ("uid", "name", "public") values ($1, $2, $3) returning *`, a.UID, a.Name, a.Public)
	if err != nil {
		return err
	}
	defer rows.Close()

	_, err = dbtool.ScanToStruct(rows, a)
	if err != nil {
		return err
	}

	return
}

// Update -
func (a *Album) Update() (err error) {
	_, err = x.Exec(`update "storage"."album" set 
		"name" = $1,
		"public" = $2
		where 
		"id" = $3`, a.Name, a.Public, a.ID)

	return
}
