package notice

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func SendChineseSMS(host, user, pass, mobile, content string) error {
	client := &http.Client{}
	req, err := http.NewRequest("POST", host, strings.NewReader("account="+user+"&password="+pass+"&mobile="+mobile+"&content="+content))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	result := struct {
		Code int    `xml:"code"`
		Msg  string `xml:"msg"`
	}{}

	err = xml.Unmarshal(body, &result)
	if err != nil {
		return err
	}

	if result.Code != 2 {
		switch result.Code {
		case 406, 4030:
			return fmt.Errorf("phone number format is not correct")
		case 4072:
			return fmt.Errorf("your message must match the templat")
		case 4081:
			return fmt.Errorf("one verification code per minute per phone")
		case 4085:
			return fmt.Errorf("up to 5 verification codes a day")
		default:
			return fmt.Errorf("send sms faild")
		}
	}

	return nil
}

func SendForeignSMS(user, pass, mobile, content string) error {
	content = url.QueryEscape(content)
	url := "http://222.73.117.140:8044/mt?dc=15&tf=3&rf=1&un=" + user + "&pw=" + pass + "&da=" + mobile + "&sm=" + content

	resp, err := http.Get(url)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	result := string(body)

	if !strings.Contains(result, "id") {
		return fmt.Errorf("phone number format is not correct")
	}

	return nil
}
