package utils

import (
	"bytes"
	"fmt"
	"net/http"
	"strings"
	"sync"

	"github.com/astaxie/beego/config"
)

// SMSEngine 短信
type SMSEngine struct {
	url         string
	method      string
	contentType string
	setting     config.Configer
}

var defaultSMS *SMSEngine
var mtx *sync.Mutex

// ResetSMSEngine 重置引擎
func ResetSMSEngine(conf config.Configer) {
	mtx.Lock()
	defer mtx.Unlock()

	newAPIURL := conf.String("url")

	if defaultSMS == nil || defaultSMS.url != newAPIURL {
		defaultSMS = &SMSEngine{
			url:         conf.String("url"),
			method:      strings.ToUpper(conf.String("method")),
			contentType: conf.String("contentType"),
			setting:     conf,
		}
	}
}

// SendSMS 发送短信
func SendSMS(smsType, tel string, messages ...string) {
	go func() {
		if defaultSMS == nil {
			LogError("没有成功初始化短信引擎")
			return
		}

		// 接口内容
		messageTpl := defaultSMS.setting.String(smsType + "::message")
		// 发送消息
		message := strings.Join(messages, `","`)
		if message != "" {
			message = fmt.Sprintf(`"%s"`, message)
		}

		// 接口 data
		data := bytes.NewBuffer([]byte(fmt.Sprintf(messageTpl, tel, message)))

		// 暂时只支持 post 发送数据
		if defaultSMS.method == http.MethodPost {
			resp, err := http.Post(defaultSMS.url, defaultSMS.contentType, data)
			if err != nil {
				LogError("短信发送错误: " + err.Error())
			}

			if resp.StatusCode != http.StatusOK {
				LogError("短信发送失败: " + resp.Status)
			}
		}

	}()
}

func init() {
	mtx = new(sync.Mutex)
}
