/**
 * Created with JetBrains WebStorm.
 * User: Cmma
 * Date: 8/11/14
 * Time: 11:24 AM
 * To change this template use File | Settings | File Templates.
 */

define(function(require, exports) {

    function RestClient() {

        var _self = this;

        var access_token = '';
        var initialzed = false;

        var _config = {
            appkey		: "Hb0YhmOo",
            appsecret	: "R7odNVS0KPtgXJ1TKQbHAxFP6EHdSW5d",
            username	: "",
            password 	: "",
            grantType  	: "client_credentials", //password
            locale 		: "zh_CN",
            format 		: "json",
            tokenUrl	: AppRemoteSvcCfg.UserSvcToken,
            restUrl		: AppRemoteSvcCfg.ResSvcUrl
        };

        this.reqAccessToken = function(user, pass, callback) {
            $.ajax({
                type: "POST",
                async: false,
                cache: false,
                url: _config.tokenUrl,
                data: {"client_id": _config.appkey, "client_secret": _config.appsecret, "grant_type": _config.grantType, "username":user, "password":pass},
                dataType: "json",
                success: function(_data) {
                    access_token = _data.access_token;
                    callback(_data.access_token);
                },
                error: function(_data) {
                    callback("");
                }
            });
        }

        this.userLogin = function(user, pass) {
            $.ajax({
                type: "POST",
                async: false,
                cache: false,
                url: _config.restUrl,
                data:{
                    "method" : "core.user.login",
                    "version" : "version",
                    "format" : "json",
                    "key" : "loginName",
                    "value" : user,
                    "password" : pass,
                    "appkey": "Hb0YhmOo",
                    "access_token" : access_token
                },
                dataType: "json",
                success:function(_data) {},
                error: function(_data) {}
            });
        }

        function innerReq(httpmethod, param) {
            var _data = {"locale": _config.locale, "format": _config.format, "appkey": _config.appkey, "access_token": access_token};
            for(var attr in param) {
                _data[attr]=param[attr];
            }

            var returnData;
            $.ajax({
                type: httpmethod,
                async: false,
                url: _config.restUrl,
                data: _data,
                dataType: _data.format,
                success: function(data) {
                    returnData = data;
                },
                error: function(jqXHR, textStatus, errorThrown){
                    //401 token
                    log(jqXHR.responseJSON)
                    if(jqXHR.status == "401" && jqXHR.responseJSON.code == "106") {
                        access_token = "";
                        returnData = RestClient._request(httpmethod, param);
                    }
                }
            });

            return returnData;
        }

        this.init = function(config) {
            if(!initialzed) {
                for(var attr in config) {
                    if(_config[attr] != undefined) {
                        _config[attr] = config[attr];
                    }
                }
                initialzed = true;
            }
        }

        this.post = function(param) {
            return _self._request("POST", param);
        }

        this.get = function(param) {
            return _self._request("GET", param);
        }

        this._request = function(httpmethod, param) {
            if(access_token == "") {
                _self.reqAccessToken();
            }
            return innerReq(httpmethod, param);
        }

    };

    exports.RestClient = new RestClient();

})