/**
 * Created with JetBrains WebStorm.
 * User: Cmma
 * Date: 7/22/14
 * Time: 10:44 AM
 * To change this template use File | Settings | File Templates.
 */

define(function(require, exports) {
    //require('appcfg');
    var restClient = require('./restclient').RestClient;

    function UserSvc() {

        this.userName = "";
        this.uuid = "";
        this.passwd = "";
        var _self = this;

        function formateParams(obj) {
            var params = "";
            for(var p in obj) {
                params += p + "=" + obj[p] + "&";
            }
            return encodeURI(params.substr(0, params.length - 1));
        }


        this.login = function(userName, password, callback) {
            _self.userName = userName;
            _self.passwd = password;
            _self.getToken(function(token) {
                if(!token) {
                    callback(401);
                    return;
                }
                var paramObj = {
                    "method" : "core.user.login",
                    "version" : "version",
                    "format" : "json",
                    "key" : "loginName",
                    "value" : userName,
                    "password" : password,
                    "appkey": "Hb0YhmOo",
                    "access_token" : token
                };

                var params = formateParams(paramObj);

                $.post(AppRemoteSvcCfg.UserSvcUrl, params, function(data) {
                    if(data) {
                        if(data.statusCode == 1) {

                            _self.uuid = data.userInfo.id;
                        }
                        callback(new Number(data.statusCode));
                    }
                    else {
                        callback(-1);
                    }
                }).error(function(data) {
                        callback(-1);
                    })
            })
        }

        this.getToken = function(callback) {

            restClient.reqAccessToken(_self.userName, _self.passwd, callback);
        }
    };



    exports.userSvc = new UserSvc();

})