package ticket

import (
	"strconv"

	"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
)

func init() {
	createTableQuery := `CREATE TABLE IF NOT EXISTS ticket (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		content TEXT NOT NULL,
		fromQQ TEXT NOT NULL,
		fromGroup TEXT DEFAULT NULL,
		isDone BOOLEAN DEFAULT FALSE,
		isDeleted BOOLEAN DEFAULT FALSE,
		created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
	);
	`
	sqlite3.TryCreateTable(createTableQuery)
}

func storeTicket(content string, fromQQ int64, fromGroup int64) (int64, error) {
	ticket := Ticket{
		Content:   content,
		FromQQ:    fromQQ,
		FromGroup: fromGroup,
	}
	tx, err := sqlite3.GetTran()
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()
	res, err := tx.Exec("INSERT INTO ticket (content, fromQQ, fromGroup) VALUES (:content, :fromQQ, :fromGroup)", ticket.Content, ticket.FromQQ, ticket.FromGroup)
	if err != nil {
		return 0, err
	}
	id, _ := res.LastInsertId()
	tx.Commit()
	return id, nil
}

func setTicketDone(id int) error {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	_, err = tx.Exec("UPDATE ticket SET isDone = TRUE WHERE id = ?", id)
	if err != nil {
		return err
	}
	tx.Commit()
	return nil
}

func getAllTicket() ([]WebTicketModel, error) {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()

	var ticketList []Ticket
	err = tx.Select(&ticketList, "SELECT * FROM ticket WHERE isDone=false")
	if err != nil {
		return nil, err
	}

	var webTickets []WebTicketModel
	for _, v := range ticketList {
		var fromQQStr string
		if v.FromQQ == 0 {
			fromQQStr = "未知"
		} else {
			fromQQStr = strconv.Itoa(int(v.FromQQ/10000)) + "****"
		}
		webTicket := WebTicketModel{
			Id:        v.Id,
			Content:   v.Content,
			FromQQ:    fromQQStr,
			CreatedAt: v.CreatedAt,
		}
		webTickets = append(webTickets, webTicket)
	}

	err = tx.Commit()
	if err != nil {
		return nil, err
	}

	return webTickets, nil
}
