package tables

import (
	"Wine-Server/utils"
)

type VersionTable struct {
	Ver  uint32 `json:"ver"`
	Name string `json:"name"`
	Url  string `json:"url"`
}

func CreateVersionTable() error {
	sql := "CREATE TABLE IF NOT EXISTS `version` (" +
		"`ver` INT UNSIGNED PRIMARY KEY NOT NULL," +
		"`name` VARCHAR(32)," +
		"`url` VARCHAR(128) NOT NULL);"
	_, err := utils.Mysql.Exec(sql)
	return err
}

func (row *VersionTable) Insert() error {
	sql := "INSERT INTO `version` (`ver`,`name`,`url`) VALUES(?,?,?);"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Ver, row.Name, row.Url)
	return err
}

func (row *VersionTable) Delete() error {
	pre, err := utils.Mysql.Prepare("DELETE FROM `version` WHERE `ver`=?;")
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Ver)
	return err
}

func (row *VersionTable) Update(args utils.JsonType) error {
	keys, values := utils.UnZip(args)
	sql := utils.Format("UPDATE `version` SET %s WHERE `ver`=%d;", utils.SqlFields(keys), row.Ver)
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(values...)
	return err
}

func (row *VersionTable) UpdateSelf() error {
	sql := "UPDATE `version` SET `name`=?,`url`=? WHERE `ver`=?;"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Name, row.Url, row.Ver)
	return err
}

func (row *VersionTable) GetLatest() error {
	sql := "SELECT `ver`,`name`,`url` FROM `version` ORDER BY `ver` DESC LIMIT 1;"
	err := utils.Mysql.QueryRow(sql).Scan(&row.Ver, &row.Name, &row.Url)
	return err
}

func VersionListAll() ([]VersionTable, error) {
	var res []VersionTable
	query, err := utils.Mysql.Query("SELECT `ver`,`name`,`url` FROM `version`;")
	if err != nil {
		return nil, err
	}
	for query.Next() {
		var one VersionTable
		err = query.Scan(&one.Ver, &one.Name, &one.Url)
		if err != nil {
			return nil, err
		}
		res = append(res, one)
	}
	return res, nil
}
