package feieapi

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

	"git.rosy.net.cn/baseapi/platformapi"
	"git.rosy.net.cn/baseapi/utils"
)

const (
	url = "http://admin.feieyun.com"
)

func (a *API) AccessStorePage(subURL string, params map[string]interface{}) (retVal map[string]interface{}, err error) {
	if a.GetCookieCount() == 0 {
		return nil, fmt.Errorf("需要设置Store Cookie才能使用此方法")
	}
	err = platformapi.AccessPlatformAPIWithRetry(a.client,
		func() *http.Request {
			request, _ := http.NewRequest(http.MethodPost, utils.GenerateGetURL(url, subURL, nil), strings.NewReader(utils.Map2URLValues(params).Encode()))
			request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			a.FillRequestCookies(request)
			return request
		},
		a.config,
		func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
			if jsonResult1 == nil {
				return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
			}
			retVal = jsonResult1
			return platformapi.ErrLevelSuccess, err
		})
	return retVal, err
}

// 设置打印机声音
func (a *API) SetSound(sn, beeperalarm string) (err error) {
	size := translateSoundSize(beeperalarm)
	_, err = a.AccessStorePage("api.php", map[string]interface{}{
		"action":       "Printer_setPrinterConfig",
		"uid":          "2013191",
		"sn":           sn,
		"printautocut": "N",
		"beeperalarm":  size,
	})
	return err
}

func translateSoundSize(beeperalarm string) (size string) {
	switch beeperalarm {
	case "0":
		size = "N"
	case "1":
		size = "U"
	case "2":
		size = "V"
	case "3":
		size = "W"
	}
	return size
}
