package kw

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

func init() {
	kwTable := `
	CREATE TABLE IF NOT EXISTS kw (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		kw TEXT,
		reply TEXT,
		group_id TEXT,
		created_by TEXT,
		created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
	);
	`
	sqlite3.TryCreateTable(kwTable)
}

func AddKW(kw string, reply string, groupID string, createdBy string) (int64, error) {
	kwData := Kw{
		Kw:        kw,
		Reply:     reply,
		GroupID:   groupID,
		CreatedBy: createdBy,
	}
	tx, err := sqlite3.GetTran()
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()
	res, err := tx.Exec("INSERT INTO kw (kw, reply, group_id, created_by) VALUES (:kw, :reply, :group_id, :created_by)", kwData.Kw, kwData.Reply, kwData.GroupID, kwData.CreatedBy)
	if err != nil {
		return 0, err
	}
	id, _ := res.LastInsertId()
	tx.Commit()
	return id, nil
}

func DeleteKW(kw string, groupID string) error {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	_, err = tx.Exec("DELETE FROM kw WHERE kw = ? AND group_id = ?", kw, groupID)
	if err != nil {
		return err
	}
	tx.Commit()
	return nil
}

func DeleteKWReply(kw string, reply string, groupID string) error {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	_, err = tx.Exec("DELETE FROM kw WHERE kw = ? AND reply = ? AND group_id = ?", kw, reply, groupID)
	if err != nil {
		return err
	}
	tx.Commit()
	return nil
}

func GetKW(kw string, groupId string) ([]Kw, error) {
	var kws []Kw
	tx, err := sqlite3.GetTran()
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()
	err = tx.Select(&kws, "SELECT * FROM kw WHERE kw = ? AND group_id = ?", kw, groupId)
	if err != nil {
		return nil, err
	}
	tx.Commit()
	return kws, nil
}

func GetGroupAllKW(groupID string) ([]Kw, error) {
	var kws []Kw
	tx, err := sqlite3.GetTran()
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()
	err = tx.Select(&kws, "SELECT * FROM kw WHERE group_id = ?", groupID)
	if err != nil {
		return nil, err
	}
	tx.Commit()
	return kws, nil
}

func GetAllKW() ([]Kw, error) {
	var kws []Kw
	tx, err := sqlite3.GetTran()
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()
	err = tx.Select(&kws, "SELECT * FROM kw")
	if err != nil {
		return nil, err
	}
	tx.Commit()
	return kws, nil
}
