package fic

import (
	"strings"
)

// GetTags returns tags associated with this exercice.
func (e *Exercice) GetTags() (tags []string, err error) {
	if rows, errr := DBQuery("SELECT tag FROM exercice_tags WHERE id_exercice = ?", e.Id); errr != nil {
		return nil, errr
	} else {
		defer rows.Close()

		tags = make([]string, 0)
		for rows.Next() {
			var t string
			if err = rows.Scan(&t); err != nil {
				return
			}
			tags = append(tags, t)
		}
		err = rows.Err()
		return
	}
}

// AddTag assign a new tag to the exercice and registers it into the database.
func (e *Exercice) AddTag(tag string) (string, error) {
	tag = strings.Title(tag)
	if _, err := DBExec("INSERT INTO exercice_tags (id_exercice, tag) VALUES (?, ?)", e.Id, tag); err != nil {
		return "", err
	} else {
		return tag, nil
	}
}

// DeleteTag delete a tag assigned to the current exercice from the database.
func (e *Exercice) DeleteTag(tag string) (int64, error) {
	if res, err := DBExec("DELETE FROM exercice_tags WHERE id_exercice = ? AND tag = ?", e.Id, tag); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// WipeTags delete all tag assigned to the current exercice from the database.
func (e *Exercice) WipeTags() (int64, error) {
	if res, err := DBExec("DELETE FROM exercice_tags WHERE id_exercice = ?", e.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}
