package wechat

// Server wechat
type Server struct {
	AppID          string `json:"appid"`
	AppSecret      string `json:"appsecret"`
	Token          string `json:"token"`
	EncodingAESKey string `json:"encodingaeskey"`
}

func keyServer(appid string) string {
	return "wechat:server:" + appid
}

// NewServer new Server
func NewServer(appID, appSecret, token, encodingAESKey string) *Server {
	key := keyServer1(appID)
	if v, ok := memcache.Load(key); ok {
		return v.(*Server)
	}
	s := &Server{AppID: appID, AppSecret: appSecret, Token: token, EncodingAESKey: encodingAESKey}
	memcache.Store(key, s)
	return s
}

// Echo notify echo GET
func (ws Server) Echo(s FormSignature) (data string, err error) {
	if ok := makeSignature(ws.Token, s.Signature, s.TimeStamp, s.Nonce); ok {
		data = s.Echostr
	}
	return
}

// Validate 验证请求合法性
func (ws Server) Validate(signature, timestamp, nonce string) bool {
	return makeSignature(ws.Token, signature, timestamp, nonce)
}