package controllers

import (
	"git.rosy.net.cn/baseapi/platformapi/weimobapi"
	"git.rosy.net.cn/jx-callback/business/cs"
	"git.rosy.net.cn/jx-callback/business/jxutils/tasks"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
)

type WeimobController struct {
	web.Controller
}

func (c *WeimobController) onCallbackMsg() {
	if true { //c.Ctx.Input.Method() == http.MethodPost {
		msg, callbackResponse := api.WeimobAPI.GetCallbackMsg(c.Ctx.Input.RequestBody)
		if callbackResponse == nil {
			// callbackResponse = wsc.OnCallbackMsg(msg)
			callbackResponse = cs.OnCallbackMsg(msg)
		}
		if callbackResponse == nil {
			callbackResponse = weimobapi.SuccessResponse
		}
		c.Data["json"] = callbackResponse
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *WeimobController) Code() {
	state := c.GetString("state")
	if state == globals.WeimobStateSecret { // 防止有人故意搞坏，添加一个secret
		code := c.GetString("code")
		token, err := api.WeimobAPI.RefreshTokenByCode(code, globals.WeimobCallbackURL+"/code")
		if err == nil {
			tasks.SaveWeimobToken(token)
		} else {
			globals.SugarLogger.Warnf("RefreshTokenByCode failed with error:%v", err)
		}
	}
}

func (c *WeimobController) Msg() {
	c.onCallbackMsg()
}
