/**
 * 核心服务接口sdk（golang版）
 *
 * @desc 啪啪运动 核心服务接口sdk
 * ---------------------------------------------------------------------
 * @author		unphp <unphp@qq.com>
 * @date		2018-12-18
 * @copyright	core-utils
 * ---------------------------------------------------------------------
 */

package cooper

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

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

type UidLockReturn struct {
	SessionID string
}

//UidLockRequest 唯一id生成器
type UidLockRequest struct {
	Client     *CooperClient
	Domain     string `json:"domain"`     //名称
	SessionID  string `json:"session_id"` //初始化开始值
	MaxActive  int64  `json:"max_active"` //最大锁资源上限
	Expire     int64  `json:"expire"`     //锁有效期
	apiAddress string
}

func (that *UidLockRequest) SetSession(domain, sessionID string, maxActive, expire int64) *UidLockRequest {
	that.Domain = domain
	that.SessionID = sessionID
	that.MaxActive = maxActive
	that.Expire = expire
	return that
}

//Params ...
func (that *UidLockRequest) Params() (url.Values, error) {
	var m = make(url.Values)
	m.Set("domain", utils.ToString(that.Domain))
	m.Set("session_id", utils.ToString(that.SessionID))
	m.Set("max_active", utils.ToString(that.MaxActive, true))
	m.Set("expire", utils.ToString(that.Expire, true))
	return m, nil
}

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