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` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY," +
		"`key` VARCHAR(32) NOT NULL," +
		"`value` INT UNSIGNED NOT NULL," +
		"`describe` VARCHAR(32) DEFAULT '');"
	_, err := utils.Mysql.Exec(sql)
	if err != nil {
		return err
	}
	return nil
}

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

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)
	if err != nil {
		return err
	}
	return nil
}

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...)
	if err != nil {
		return err
	}
	return nil
}

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)
	if err != nil {
		return err
	}
	return nil
}

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)
	if err != nil {
		return err
	}
	return nil
}

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
}
