package kfccrazy

import (
	"strings"
	"time"

	"git.lxtend.com/lixiangwuxian/qqbot/constants"
	"git.lxtend.com/lixiangwuxian/qqbot/handler"
	"git.lxtend.com/lixiangwuxian/qqbot/model"
	"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
	"git.lxtend.com/lixiangwuxian/qqbot/util"
)

func init() {
	// handler.RegisterHelpInform("疯狂星期四", "疯狂星期四", "随机输出疯狂星期四文案")
	// handler.RegisterHandler("疯狂星期四", pickKfc, constants.LEVEL_USER)
	// handler.RegisterHelpInform("疯狂星期四文案添加", "疯狂星期四文案添加", "添加疯狂星期四文案")
	handler.RegisterHandler("疯狂星期四文案添加", storeKfc, constants.LEVEL_TRUSTED)

	// 创建疯狂星期四文案表
	createTableSQL := `CREATE TABLE IF NOT EXISTS kfc_crazy (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		content TEXT NOT NULL,
		created_by TEXT NOT NULL,
		created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
	);`
	sqlite3.TryCreateTable(createTableSQL)
}

func storeKfc(msg model.Message) (reply *model.Reply) {
	// 分割消息获取文案内容
	tokens := util.SplitN(msg.RawMsg, 2)
	if len(tokens) < 2 {
		return &model.Reply{
			ReplyMsg:       "请输入要添加的疯狂星期四文案",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	content := strings.TrimSpace(tokens[1])
	if content == "" {
		return &model.Reply{
			ReplyMsg:       "文案内容不能为空",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	// 存储文案到数据库
	tx, err := sqlite3.GetTran()
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "数据库错误",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	defer tx.Rollback()

	_, err = tx.Exec("INSERT INTO kfc_crazy (content, created_by) VALUES (?, ?)", content, msg.UserId)
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "保存文案失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	err = tx.Commit()
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "保存文案失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	return &model.Reply{
		ReplyMsg:       "文案添加成功",
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func pickKfc(msg model.Message) (reply *model.Reply) {
	// 判断是否是周四
	if time.Now().Weekday() != time.Thursday {
		return nil
	}
	// 从数据库随机获取一条文案
	tx, err := sqlite3.GetTran()
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "数据库错误",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	defer tx.Rollback()

	var count int
	err = tx.Get(&count, "SELECT COUNT(*) FROM kfc_crazy")
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "获取文案失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	if count == 0 {
		return nil
	}

	var content string
	err = tx.Get(&content, "SELECT content FROM kfc_crazy ORDER BY RANDOM() LIMIT 1")
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "获取文案失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	err = tx.Commit()
	if err != nil {
		return &model.Reply{
			ReplyMsg:       "获取文案失败",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}

	return &model.Reply{
		ReplyMsg:       content,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
