package tables

import (
	"Wine-Server/utils"
	"fmt"
)

type ManagerTable struct {
	Id    string
	Super bool
	First utils.TimeType
	Last  utils.TimeType

	Name     string
	Account  string
	Password string

	OrderCount  uint32
	TotalIncome float64
}

func CreateManagerTable() error {
	sql := "CREATE TABLE IF NOT EXISTS `manager`(" +
		"`id` VARCHAR(16) PRIMARY KEY," +
		"`super` BOOL DEFAULT FALSE," +
		"`first` DATETIME DEFAULT CURRENT_TIMESTAMP," +
		"`last` DATETIME DEFAULT CURRENT_TIMESTAMP," +
		"`name` VARCHAR(16) NOT NULL," +
		"`account` VARCHAR(32) NOT NULL," +
		"`password` VARCHAR(512) NOT NULL," +
		"`order` INT UNSIGNED DEFAULT 0," +
		"`income` DOUBLE DEFAULT 0);"
	_, err := utils.Mysql.Exec(sql)
	if err != nil {
		return err
	}
	return nil
}

func (row *ManagerTable) Insert() error {
	sql := "INSERT INTO `manager` (`id`, `name`, `account`, `password`) VALUES (?, ?, ?, ?);"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	_, err = pre.Exec(row.Id, row.Name, row.Account, row.Password)
	if err != nil {
		return err
	}
	return nil
}

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

func (row *ManagerTable) Update(args utils.JsonType) error {
	keys, values := utils.UnZip(args)
	sql := fmt.Sprintf("UPDATE `manager` 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 *ManagerTable) Get() error {
	sql := "SELECT `super`, `first`, `last`, `name`, `account`, `password`, `count`, `income` FROM `manager` WHERE `id`=?;"
	pre, err := utils.Mysql.Prepare(sql)
	if err != nil {
		return err
	}
	err = pre.QueryRow(row.Id).Scan(&row.Super, &row.First, &row.Last, &row.Name, &row.Account, &row.Password, &row.OrderCount, &row.TotalIncome)
	if err != nil {
		return err
	}
	return nil
}
