package tables

import (
	"Wine-Server/utils"
)

type TradeTable struct {
	Id      string         `json:"id"`
	Trade   string         `json:"trade"`
	Device  string         `json:"device"`
	Time    utils.TimeType `json:"time"`
	Payer   string         `json:"payer"`
	Wine    uint16         `json:"wine"`
	Weight  uint16         `json:"weight"`
	Cash    int            `json:"cash"`
	Manager string         `json:"manager"`
}

func CreateTradeTable() error {
	sql := "CREATE TABLE IF NOT EXISTS `trade`(" +
		"`id` VARCHAR(32) PRIMARY KEY NOT NULL," +
		"`trade` VARCHAR(64) NOT NULL," +
		"`device` VARCHAR(32) NOT NULL," +
		"`time` DATETIME DEFAULT CURRENT_TIMESTAMP," +
		"`payer` VARCHAR(64) NOT NULL," +
		"`wine` SMALLINT UNSIGNED NOT NULL," +
		"`weight` SMALLINT UNSIGNED NOT NULL," +
		"`cash` INT UNSIGNED NOT NULL," +
		"`manager` VARCHAR(16));"
	_, err := utils.Mysql.Exec(sql)
	if err != nil {
		return err
	}
	return nil
}

func (row *TradeTable) Insert() error {
	sql := "INSERT INTO `trade`(`id`,`trade`,`device`,`payer`,`wine`,`weight`,`cash`,`manager`) VALUES(?,?,?,?,?,?,?,?);"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Id, row.Trade, row.Device, row.Payer, row.Wine, row.Weight, row.Cash, row.Manager)
	if err != nil {
		return err
	}
	return nil
}

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

func (row *TradeTable) Update(args utils.JsonType) error {
	keys, values := utils.UnZip(args)
	sql := utils.Format("UPDATE `trade` SET %s WHERE `id`=%s;", 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 *TradeTable) UpdateSelf() error {
	sql := "UPDATE `trade` SET `trade`=?,`device`=?,`time`=?,`payer`=?,`wine`=?,`weight`=?,`cash`=?,`manager`=? WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Trade, row.Device, row.Time, row.Payer, row.Wine, row.Weight, row.Cash, row.Manager, row.Id)
	if err != nil {
		return err
	}
	return nil
}

func (row *TradeTable) Get() error {
	sql := "SELECT `trade`,`device`,`time`,`payer`,`wine`,`weight`,`cash`,`manager` FROM `trade` WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	err = pre.QueryRow(row.Id).Scan(
		&row.Trade, &row.Device, &row.Time, &row.Payer,
		&row.Wine, &row.Weight, &row.Cash, &row.Manager,
	)
	if err != nil {
		return err
	}
	return nil
}

// TODO: list by: <device>, <manager>, <payer> with time-duration
