angular.module('carfriend.services', [])
        .service('APIInterceptor', function ($rootScope, $q) {
            var service = this;

            service.responseError = function (response) {
                if (response.status === 401) {
                    $rootScope.$broadcast('unauthorized');
                }
                return $q.reject(response);
            };
        })
     /*   .service('UserService', function ($http, Backand) {
            var service = this,
                    baseUrl = '/1/objects/',
                    object = 'users/';

            function getUrl() {
                return Backand.getApiUrl() + baseUrl + object;
            }

            function getUrlForId(id) {
                return getUrl() + id;
            }
            service.update = function (id, object) {
                return $http.put(getUrlForId(id), object);
            };
        }) */

        /*.service('CarSvice______________________________________________________', function ($http, Backand, $q) {
            var service = this,
                    baseUrl = '/1/objects/',
                    object = 'cars/';

            function getUrl() {
                return Backand.getApiUrl() + baseUrl + object;
            }

            function getUrlForId(id) {
                return getUrl() + id;
            }

            service.all = function () {
                return $http.get(getUrl());
            };

            service.fetch = function (id) {
                return $http.get(getUrlForId(id));
            };
            
            service.findCarByEvc = function (evc) {
                var deffered = $q.defer();
                $http({
                    method: 'GET',
                    url: getUrl(),
                    params: {
                        filter: JSON.stringify([{
                                "fieldName": "evidenceNumber",
                                "operator": "equals",
                                "value": evc
                            }])
                    }
                }).then(function (response) {
                    deffered.resolve(response);
                }, function (error) {
                    deffered.reject(error);
                })
                return deffered.promise;
            };

            //check if license plate is in system
//            service.findCarByEvc = function (evc) {
//                return $http({
//                    method: 'GET',
//                    url: getUrl(),
//                    params: {
//                        filter: JSON.stringify([{
//                                "fieldName": "evidenceNumber",
//                                "operator": "equals",
//                                "value": evc
//                            }])
//                    }
//                }).then(function (response) {
//                    if (response.data && response.data.data && response.data.data.length == 1) {
//                        return true;
//                    } else {
//                        //not found
//                        return false
//                    }
//                });
//            };
            service.getUserByCarId = function (carid) {
                return $http({
                    method: 'GET',
                    url: getUrl(),
                    params: {
                        filter: JSON.stringify([{
                                "fieldName": "id",
                                "operator": "equals",
                                "value": carid
                            }]),
                        deep: true
                    },
                }).then(function (response) {
                    if (response.data && response.data.data && response.data.data.length == 1) {
                        return response.data.data[0].__metadata.descriptives.user.label;
                    } else {
                        return null;
                    }
                });
            }


            service.getUserCars = function (userId) {

                return $http({
                    method: 'GET',
                    url: getUrl(),
                    params: {
                        filter: JSON.stringify([{
                                "fieldName": "user",
                                "operator": "in",
                                "value": userId
                            }])
                    }
                }).then(function (response) {
                    if (response.data && response.data.data) {
                        return response.data.data[0];
                    }
                });
            }

            service.search = function (evc, color) {
                return service.findCarByEvc(evc).then(function (found) {
                    console.log(found);
                    if (found) {
                        return $http({
                            method: 'GET',
                            url: getUrl(),
                            params: {
                                filter: JSON.stringify([{
                                        "fieldName": "evidenceNumber",
                                        "operator": "equals",
                                        "value": evc
                                    }, {
                                        "fieldName": "color",
                                        "operator": "equals",
                                        "value": color
                                    }])
                            }
                        }).then(function (response) {
                            if (response.data && response.data.data && response.data.data.length == 1) {
                                return response.data.data[0];
                            } else {
                                return "no match"
                            }
                        }, function (error) {
                            console.log(error);
                        });
                    } else {
                        //this evidence number is not registered. Notification is possible to send althought
                        return "no registered"
                    }
                })
            };

            service.create = function (object) {
                return $http.post(getUrl(), object);
            };

            service.update = function (id, object) {
                return $http.put(getUrlForId(id), object);
            };

            service.delete = function (id) {
                return $http.delete(getUrlForId(id));
            };
        })*/

     /*   .factory('AuthService', function ($http, Backand) {
            var baseUrl = Backand.getApiUrl() + '/1/objects/';
            var object = 'users/';
            
            var currentUser = {};

            var services = {
                fetch: fetch,
                loadUserDetails: loadUserDetails,
                signIn: signIn,
                signUp: signUp,
                signout: signout,
                returnUser: returnUser,
                returnCurrentUser: returnCurrentUser,
                currentUser: currentUser
            };
            return services;
            
            ///////////////
            
            function fetch(id) {
                return $http.get(baseUrl + object + id);
            };

            function loadUserDetails() {
                console.log("AuthService. Start loading user details");
                currentUser.username = Backand.getUsername();
                if (currentUser.username) {
                    getCurrentUserInfo(currentUser.username).then(function (data) {
                        currentUser.details = data;
                        console.log("AuthService. User loaded: ", currentUser);
                    });
                }
            }

            function signIn(username, password) {
                return Backand.signin(username, password).then(function (response) {
                    console.log("res", response);
                    loadUserDetails();
                    console.log("Backand.getToken()", Backand.getToken());
                    return response;
                });
            };

            function signUp (firstName, lastName, email, password, again, parameters) {
                return Backand.signup(firstName, lastName, email, password, again, parameters);
            };


            function signout() {
                return  Backand.signout().then(function () {
                    angular.copy({}, currentUser);
                    console.log("Backand.getToken()", Backand.getToken());
                });
            };

             function returnUser() {
                console.log("AuthService. Return currentUSer: ", service.currentUser);
                return currentUser;
            };

            function returnCurrentUser() {
                return getCurrentUserInfo(Backand.getUsername());
            };

            function getCurrentUserInfo(email) {
                return $http({
                    method: 'GET',
                    url: baseUrl + "users",
                    params: {
                        filter: JSON.stringify([{
                                fieldName: "email",
                                operator: "equals",
                                value: email
                            }])
                    }
                }).then(function (response) {
                    if (response.data && response.data.data && response.data.data.length == 1)
                        return response.data.data[0];
                });
            }

            //  loadUserDetails();


            //            service.changePassword = function (oldPassword, newPassword) {
//                return Backand.changePassword(oldPassword, newPassword)
//            };
//
//            service.requestResetPassword = function (username) {
//                return Backand.requestResetPassword(username, service.appName)
//            };
//
//            service.resetPassword = function (password, token) {
//                return Backand.resetPassword(password, token)
//            };

        }) */

        /*.service('ColorService', function () {
            var service = this;
            service.colorsOffer = {
                "reddie": "#ff0000",
                "canaryblue": "#b3f5ff"
            };
            service.getColors = function () {
                return service.colorsOffer;
            }
        })*/

       /* .factory('LoadingService', function ($ionicLoading) {
            return {
                startLoad: function () {
                    $ionicLoading.show({
                        content: 'Loading',
                        showBackdrop: true,
                        noBackdrop: true,
                        maxWidth: 200,
                        showDelay: 0,
                        template: '<ion-spinner icon="ripple"/>'
                    })
                },
                completeLoad: function () {
                    $ionicLoading.hide();
                }
            }
        })*/

       /* .factory('NotificationService', function (Backand, $http, $q, $filter) {
            var victimID = '';

            var baseUrl = Backand.getApiUrl() + '/1/objects/notifications';

            return {
                getVictimID: function () {
                    return victimID;
                },
                setVictimID: function (id) {
                    victimID = id;
                },
                sendNotification: function (notif) {
                    console.log(notif)
                    var deffered = $q.defer();
                    $http({
                        method: 'POST',
                        url: baseUrl, // + '??returnObject=true',
                        params: {
                            parameters: {
                                email: notif.userEmail
                            }
                        },
                        data: {
                            situation: notif.situation,
                            datetime: notif.datetime,
                            message: notif.message,
                            datetime: $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss'),
                                    from: notif.from,
                            to: victimID,
                            photo: notif.photo,
                            lat: notif.gps.lat,
                            lang: notif.gps.lang
                        }
                    }).then(function (response) {
                        victimID = '';
                        deffered.resolve(response);

                    }, function (error) {
                        deffered.reject(error);
                    })
                    return deffered.promise;
                },
                getNotifications: function (car) {
                    var deffered = $q.defer();
                    $http({
                        method: 'GET',
                        url: Backand.getApiUrl() + '/1/query/data/getNotifications',
                        params: {
                            pageSize: 6,
                            pageNumber: 1,
                            filter: null,
                            deep: true,
                            sort: [{
                                    "fieldName": "datetime",
                                    "order": "desc"
                                }],
                            parameters: {
                                evidenceNumber: car
                            }
                        }
                    }).then(function (response) {
                        console.log(response);
                        deffered.resolve(response);
                    }, function (error) {
                        deffered.reject(error);
                    });
                    return deffered.promise;
                },
                getSendNotifications: function (from) {
                    var deffered = $q.defer();
                    $http({
                        method: 'GET',
                        url: baseUrl,
                        params: {
                            deep: true,
                            sort: [{
                                    "fieldName": "datetime",
                                    "order": "desc"
                                }],
                            filter: JSON.stringify([{
                                    "fieldName": "from",
                                    "operator": "in",
                                    "value": from
                                }])
                        }
                    }).then(function (response) {
                        console.log("FROM:", response);
                        deffered.resolve(response);
                    }, function (error) {
                        deffered.reject(error);
                    });
                    return deffered.promise;
                },
                getReceivedNotifications: function (to) {
                    var deffered = $q.defer();
                    $http({
                        method: 'GET',
                        url: baseUrl,
                        params: {
                            deep: true,
                            sort: [{
                                    "fieldName": "datetime",
                                    "order": "desc"
                                }],
                            filter: JSON.stringify([{
                                    "fieldName": "to",
                                    "operator": "in",
                                    "value": to
                                }])
                        }
                    }).then(function (response) {
                        console.log("TO:", response);
                        deffered.resolve(response);
                    }, function (error) {
                        deffered.reject(error);
                    });
                    return deffered.promise;
                },
                getNewNotifications: function (car) {
                    var deffered = $q.defer();
                    $http({
                        method: 'GET',
                        url: baseUrl,
                        params: {
                            deep: true,
                            sort: [{
                                    "fieldName": "datetime",
                                    "order": "desc"
                                }],
                            filter: JSON.stringify([{
                                    "fieldName": "to",
                                    "operator": "in",
                                    "value": car
                                }, {
                                    "fieldName": "rated",
                                    "operator": "empty",
                                    "value": ''
                                }])
                        }
                    }).then(function (response) {
                        deffered.resolve(response);
                    }, function (error) {
                        deffered.reject(error);
                    });
                    return deffered.promise;
                },
                thankNotification: function (notifID) {
                    var deffered = $q.defer();
                    $http({
                        method: 'PUT',
                        url: baseUrl + '/' + notifID,
                        data: {
                            thanked: true
                        }
                    }).then(function (response) {
                        deffered.resolve(response);
                    }, function (error) {
                        deffered.reject(error);
                    });
                    return deffered.promise;
                },
                rateNotification: function (notifID, rate) {
                    console.log(rate);
                    var deffered = $q.defer();
                    $http({
                        method: 'PUT',
                        url: baseUrl + '/' + notifID,
                        data: {
                            rated: rate
                        }
                    }).then(function (response) {
                        deffered.resolve(response);
                    }, function (error) {
                        deffered.reject(error);
                    });
                    return deffered.promise;
                },
            };
        })
*/

      /*  .factory('geolocationService', function ($q, $timeout, $cordovaGeolocation) {
            var currentPosition;
            var posOptions = {timeout: 10000, enableHighAccuracy: false};
            var geocoder = new google.maps.Geocoder;

            return {
                getCurrentPosition: function () {
                    if (!currentPosition) {
                        var deffered = $q.defer();
                        $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                            deffered.resolve(currentPosition = position);
                            $timeout(function () {
                                currentPosition = undefined;
                            }, 10000);
                        }, function (err) {
                            deffered.reject(err);
                        });
                        return deffered.promise;
                    }
                    return $q.when(currentPosition);
                },
                getCurrentLocation: function (position) {
                    var deferred = $q.defer();
                    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                    geocoder.geocode({'location': latlng}, function (results, status) {
                        if (status === google.maps.GeocoderStatus.OK) {
                            deferred.resolve(results);
                        } else {
                            deferred.reject("Couldn't find that address! Google Maps says: " + status);
                        }
                    });
                    return deferred.promise;
                }
            };
        })*/
        .factory('Chats', function () {
            // Might use a resource here that returns a JSON array

            // Some fake testing data
            var chats = [
                {
                    _id: 1,
                    name: 'Max Lynx',
                    picture: 'https://avatars3.githubusercontent.com/u/11214?v=3&s=460',
                    lastMessage: {
                        text: 'Hey, it\'s me'
                    }
                },
                {
                    _id: 2,
                    name: 'Adam Bradleyson',
                    picture: 'https://pbs.twimg.com/profile_images/479090794058379264/84TKj_qa.jpeg',
                    lastMessage: {
                        text: 'I should buy a boat'
                    }
                },
                {
                    _id: 3,
                    name: 'Perry Governor',
                    picture: 'https://pbs.twimg.com/profile_images/598205061232103424/3j5HUXMY.png',
                    lastMessage: {
                        text: 'Look at my mukluks!'
                    }
                }
            ];


            return {
                all: function () {
                    return chats;
                },
                remove: function (chat) {
                    chats.splice(chats.indexOf(chat), 1);
                },
                get: function (chatId) {
                    for (var i = 0; i < chats.length; i++) {
                        if (chats[i]._id === parseInt(chatId)) {
                            return chats[i];
                        }
                    }
                    return null;
                }
            };
        });
