package main

import (
	"fmt"
	"strings"
	"time"
)

type commandFunction func(*openIDSessionData, InWechatMsg) bool

var commandMap = map[string]commandFunction{
	"版本信息":    cmdVersion,
	"version": cmdVersion,
	//"所有命令": allCommand, //include it  will cause initialization loop
	"echo": cmdEcho,
	"回音":   cmdEcho,
}

func (ss *openIDSessionData) serveCommand(in InWechatMsg) (processed bool) {
	switch in.header.MsgType {
	case "text":
		processed = ss.serveTextCommand(in)
	case "image":
		in.replyText("图片收到")
		processed = true
	case "voice":
		processed = ss.serveTextCommand(in)
	case "video":
	case "shortvideo":
	case "location":
	case "link":
	case "event":
		processed = ss.serveEvents(in)
	default:
		processed = false
	}
	return

}

func (ss *openIDSessionData) serveTextCommand(in InWechatMsg) (processed bool) {
	cmd := ""
	if in.header.MsgType == "text" {
		cmd = in.body.(TextMsg).Content
	} else if in.header.MsgType == "voice" {
		cmd = voice2Cmd(in.body.(VoiceMsg))
	}
	if cmd != "" {
		if f, hasFunction := commandMap[cmd]; hasFunction {
			return f(ss, in)
		}
		if cmd == "所有命令" || cmd == "all command" {
			return allCommand(ss, in)
		}
	}
	return false //不认识的命令，我们选择这个信息不处理
}

func allCommand(ss *openIDSessionData, in InWechatMsg) (processed bool) {
	processed = true
	msg := "命令如下:\n"
	count := 0
	for k := range commandMap {
		count++
		msg = msg + fmt.Sprintf("%0d : %s \n", count, k)
	}

	in.replyText(msg)
	return
}

func cmdVersion(ss *openIDSessionData, in InWechatMsg) (processed bool) {
	processed = true
	in.replyText("这是测试版本" + time.Now().Format("2006/01/02 03:04:05"))
	return
}

func cmdEcho(ss *openIDSessionData, in InWechatMsg) (processed bool) {
	processed = true
	in.replyText("请输入不同类型的微信信息，比如文字，图片，视频，地址，链接，我们将原样回应您")
	procEcho.init(ss)
	procEcho.intro(ss)
	procEcho.start(ss, in)
	return
}

func voice2Cmd(v VoiceMsg) (cmd string) {
	cmd = v.Recognition
	cmd = strings.TrimSuffix(cmd, "。") //去掉末尾的标点符号，句号
	return
}
