//var baseUrl="http://test.apalabrados.com/api";
var baseUrl="http://apalabrados.com/api";
angular.module('starter.factories', [])

  .factory('$awordedFactory', ['$q','$http', '$rootScope', function ($q, $http, $rootScope) {

    return {
      getPostReqData: function (method, path, data, headers) {
        var q = $q.defer();
        var req = {
                method: method,
                url: path,
                headers: headers,
                data:data
            };
        $http(req).success(function(data, status, headers, config) {
                //postResposeData = data;

                if(data.code == 412){
                    $rootScope.gameCreationErrorClose = true;
                    $rootScope.errorText="You have been added to the list. You will be notified when we find a match for you.";
                }else if(data.code == 401){
                    $rootScope.gameCreationErrorClose = true;
                    $rootScope.errorText="The shift is not valid.";
                }else if(data.code == 7){
                    $rootScope.gameCreationErrorClose = true;
                    $rootScope.errorText="Unknown Error.";
                }else if(data.code== 404){
                    $rootScope.gameCreationErrorClose = true;
                    $rootScope.errorText="Game Ended.";
                }else if( data.code == 2011){
                    $rootScope.gameCreationErrorClose = true;
                    $rootScope.errorText="Not enough coins";
                }
                $rootScope.loading_view = false;
				q.resolve(data);
                //$scope.resopnseHeader = headers;
                //callback(postResposeData);
            }).error(function(data, status, headers, config) {
                    $rootScope.loading_view =false;
                    if(data.code == 412){
                        $rootScope.gameCreationErrorClose = true;
                        $rootScope.errorText="A random game for that language is already requested.";
                    }else if(data.code == 400){
                        $rootScope.gameCreationErrorClose = true;
                        $rootScope.errorText="Word is Invalid.";
                    }else if(data.code == 100){
                        $rootScope.gameCreationErrorClose = true;
                        $rootScope.errorText="Invalid Position.";
                    }else if(data.code == 604){
                        alert("Invalid Password");
                    }else if(data.code == 301){
                        alert("Invalid User");
                    }else if(data.code == 202){
                        alert("Invalid Mail Characters");
                    }else if(data.code == 7){
                        $rootScope.gameCreationErrorClose = true;
                        $rootScope.errorText="Unknown Error.";
                    }else if( data.code == 2011){
                        $rootScope.gameCreationErrorClose = true;
                        $rootScope.errorText="Not enough coins";
                    }else {
                        $rootScope.gameCreationErrorClose = true;
                        $rootScope.errorText="Unknown Error.";
                    }
		q.reject(data);
                });
	return q.promise;
      },
	
       getReqData: function (method, path, data, headers) {
        var q = $q.defer();
	var req = {
                method: method,
                url: path,
                crossDomain: true,
                headers: headers,
                params:data
            }
         $http(req).success(function(data, status, headers, config) {
                $rootScope.loading_view =false;
		q.resolve(data);
          }).error(function(data, status, headers, config) {
                $rootScope.loading_view =false;
		q.reject(status);
          });
        return q.promise;
      },
	  
	  getLoginDetails: function(loginDetails){
		var q = $q.defer();
		$rootScope.postHeaders = {
				'Content-Type': 'application/json',
				'Accept': 'application/json',
				'etergames-referer': "Access-Control-Request-Headers"
		};
		this.getPostReqData('POST', baseUrl+'/login', loginDetails, $rootScope.postHeaders)
		.then(function(response) {
			$rootScope.loginUserData=response;
			$rootScope.getHeaders = {
				'Content-Type': 'multipart/form-data',
				'Accept': 'application/json',
				'etergames-referer': "Access-Control-Request-Headers"
			};
			$rootScope.getHeaders['Eter-Session'] = 'ap_session='+$rootScope.loginUserData.session.session;
			$rootScope.postHeaders['Eter-Session'] = 'ap_session='+$rootScope.loginUserData.session.session;
			//console.log('loginUserData '+JSON.stringify(response));
			
			var data ={"smart_ready":"true","app_config_version":"0"};
			var req = {
				method: "GET",
				url: baseUrl+'/users/'+$rootScope.loginUserData.id+'/games',
				crossDomain: true,
				headers: $rootScope.getHeaders,
				params:data
			}
			$http(req).success(function(data, status, headers, config) {
				$rootScope.profileData=data;
				data['signSucess'] = true;
				q.resolve(data);
			},function(err){}
			);
		}, function(err) {
			err['signSucess'] = false;
			q.resolve(err);
		});
		
		return q.promise;
	  },
	  getJSONObjects: function(obj, key, val) {
		var objects = [];
		for (var i in obj) {
			if (!obj.hasOwnProperty(i)) continue;
			if (typeof obj[i] == 'object') {
				objects = objects.concat(this.getJSONObjects(obj[i], key, val));    
			} else 
			//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
			if (i == key && obj[i] == val || i == key && val == '') { //
				objects.push(obj);
			} else if (obj[i] == val && key == ''){
				//only add if the object is not already in the array
				if (objects.lastIndexOf(obj) == -1){
					objects.push(obj);
				}
			}
		}
		return objects;
	  },
	  getchatHeaders : function() {
		var q = $q.defer();
		var data= {}, d=[], w=0, values;
		this.getReqData('GET', baseUrl+'/users/'+$rootScope.loginUserData.id+'/chatHeaders', data, $rootScope.getHeaders)
			.then(function (response){
					var res = response.chat_headers[0];
					for(var r in res){
						if(res[r].unread_count >= 1){
							w = w+res[r].unread_count;
							d['count']=true;
							d['numberofchat'] = w;
						}
						if(res[r].user.facebook_name != undefined  && res[r].user.fb_show_name == true){
							var oppusername = res[r].user.facebook_name;
						}else{
							var oppusername = res[r].user.username;
						}
						values = {user_id: res[r].user.id,username:oppusername,last_text:res[r].last_text, unread_count: res[r].unread_count, online_status:res[r].user.online_status};
						d.push(values);
						q.resolve(d);
					}
				},function(err){
					console.log('error'+JSON.stringify(err));
				}
			); 
		return q.promise;
	  },
	  
    }
  }]);
