package tables

import "Wine-Server/utils"

type OperationTable struct {
	Id       string         `json:"id"`
	Who      string         `json:"who"`
	Time     utils.TimeType `json:"time"`
	Describe string         `json:"describe"`
}

func CreateOperationTable() error {
	SQL := "CREATE TABLE IF NOT EXISTS `operation`(" +
		"`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL," +
		"`who` VARCHAR(32) NOT NULL," +
		"`time` DATETIME DEFAULT CURRENT_TIMESTAMP," +
		"`describe` VARCHAR(128) DEFAULT '');"
	_, err := utils.Mysql.Exec(SQL)
	return err
}

func (row *OperationTable) Insert() error {
	SQL := "INSERT INTO `operation`(`who`,`describe`) VALUES(?,?);"
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Who, row.Describe)
	return err
}

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

func (row *OperationTable) Update(args utils.JsonType) error {
	keys, values := utils.UnZip(args)
	SQL := utils.Format("UPDATE `operation` 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 *OperationTable) UpdateSelf() error {
	SQL := "UPDATE `operation` SET `who`=?,`time`=?,`describe`=? WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	row.Time = utils.TimeNow()
	_, err = pre.Exec(row.Who, row.Time, row.Describe, row.Id)
	return err
}

func (row *OperationTable) Get() error {
	SQL := "SELECT `who`,`time`,`describe` FROM `operation` WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(SQL)
	if err != nil {
		return err
	}
	err = pre.QueryRow(row.Id).Scan(&row.Who, &row.Time, &row.Describe)
	return err
}
