package pass

import (
	"PPOSUtils/utils"
	"errors"
	"net/url"
)

//NewUidGet ...
func (that *PassClient) NewUidLock() *UidLockRequest {
	return &UidLockRequest{
		Request: Request{
			Client:     that,
			apiAddress: "/mix/getLock",
		},
	}
}

type UidLockReturn struct {
	SessionID string
}

//UidLockRequest 唯一id生成器
type UidLockRequest struct {
	Request
}

func (that *UidLockRequest) SetSession(domain, sessionID string, maxActive, expire int64) *UidLockRequest {
	that.initParams()
	that.params.Set("domain", domain)                        //名称
	that.params.Set("session_id", sessionID)                 //初始化开始值
	that.params.Set("max_active", utils.ToString(maxActive)) //最大锁资源上限
	that.params.Set("expire", utils.ToString(expire))        //锁有效期
	return that
}

//Params ...
func (that *UidLockRequest) Params() (url.Values, error) {
	that.initParams()
	_params := that.params
	if that.publicParamsSlice != nil {
		for _, _v := range that.publicParamsSlice {
			if _params.Get(_v) == "" {
				return nil, errors.New(that.apiAddress + "缺少参数:" + _v)
			}
		}
	}
	return _params, nil
}

//Do ...
func (that *UidLockRequest) Do() (*UidLockReturn, error) {
	_data, _err := that.Client.GetData(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	_sessionID := ""
	switch _v := _data.(type) {
	case map[string]interface{}:
		_sessionID = utils.ToString(_v["session_id"], true)
	case string:
		_sessionID = _v
	case int64:
		_sessionID = utils.ToString(_v, true)
	case int:
		_sessionID = utils.ToString(_v, true)
	}
	return &UidLockReturn{_sessionID}, nil
}
