package tables

import (
	"Wine-Server/utils"
)

type ParamsTable struct {
	Id       uint32 `json:"id"`
	Key      string `json:"key"`
	Value    uint32 `json:"value"`
	Describe string `json:"describe"`
}

func CreateParamsTable() error {
	sql := "CREATE TABLE IF NOT EXISTS `params`(" +
		"`id` SMALLINT UNSIGNED PRIMARY KEY," +
		"`key` VARCHAR(32) NOT NULL," +
		"`value` INT UNSIGNED NOT NULL," +
		"`describe` VARCHAR(32) DEFAULT '');"
	_, err := utils.Mysql.Exec(sql)
	return err
}

// Insert deprecated
func (row *ParamsTable) Insert() error {
	sql := "INSERT INTO `params`(`key`,`value`,`describe`) VALUES(?,?,?);"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Key, row.Value, row.Describe)
	return err
}

// Delete deprecated
func (row *ParamsTable) Delete() error {
	pre, err := utils.Mysql.Prepare("DELETE FROM `params` WHERE `id`=?;")
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Id)
	return err
}

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

func (row *ParamsTable) UpdateSelf() error {
	sql := "UPDATE `params` SET `key`=?,`value`=?,`describe`=? WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Key, row.Value, row.Describe, row.Id)
	return err
}

func (row *ParamsTable) Get() error {
	sql := "SELECT `key`,`value`,`describe` FROM `params` WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	err = pre.QueryRow(row.Id).Scan(&row.Key, &row.Value, &row.Describe)
	return err
}

func ParamsListAll() ([]ParamsTable, error) {
	var res []ParamsTable
	query, err := utils.Mysql.Query("SELECT `id`,`key`,`value`,`describe` FROM `params`;")
	if err != nil {
		return nil, err
	}
	for query.Next() {
		var one ParamsTable
		err = query.Scan(&one.Id, &one.Key, &one.Value, &one.Describe)
		if err != nil {
			return nil, err
		}
		res = append(res, one)
	}
	return res, nil
}

func ParamsListAllForSuper() ([]utils.JsonType, error) {
	query, err := utils.Mysql.Query("SELECT `id`,`value`,`describe` FROM `params`;")
	if err != nil {
		return nil, err
	}
	var res []utils.JsonType
	for query.Next() {
		var one ParamsTable
		err = query.Scan(&one.Id, &one.Value, &one.Describe)
		if err != nil {
			return nil, err
		}
		res = append(res, utils.JsonType{"id": one.Id, "name": one.Describe, "value": one.Value})
	}
	return res, nil
}
