app.ng.service("entityController", ["$rootScope", "$http", "$state", "$q", "growl", function ($rootScope, $http, $state, $q, growl) {

    var params = {};

    this.load = function (entityId, entityName) {

        params.entityId = entityId;
        params.entityName = entityName;

        if (!entityId) {
            params.entityId = $state.params.entityId;
        }

        if (!entityName) {
            params.entityName = $state.params.entityName;
        }

        return $q(function (resolve, reject) {
            if (parseInt(params.entityId, 10)) {

                var promise = $q(function (resolve, reject) {
                    $rootScope.$broadcast('loaderStart', {});
                    var url = app.root + '/Api/' + params.entityName + '/' + params.entityId;
                    $http.get(url, {}).success(function (result) {
                        this.entity = result;
                        $rootScope.$broadcast('loaderEnd', {});
                        resolve(result);
                    }).error(function (err) {
                        resolve(reject(err));
                        $rootScope.$broadcast('loaderEnd', {});
                    });
                });

                promise.then(function (entity) {
                    resolve(entity);
                }, function (reason) {
                    reject(reason);
                });
            }
            else {
                this.entity = {}
                resolve({CanEdit:true});
            }
        });
    }


    this.save = function (entity) {
        return $q(function (resolve, reject) {
            $rootScope.$broadcast('loaderStart', {});
            var url = app.root + '/Api/' + params.entityName + '/Update';
            $http.post(url, entity).success(function (result) {
             
                $rootScope.$broadcast('loaderEnd', {});
                if (!parseInt(params.entityId, 10)) {
                    $state.go(params.entityName + '.Details', { entityId: result.Id });
                }
                else {
                    resolve(result);
                }
            });
        })
    }

    this.delete = function (entity) {
        if (confirm("Are you sure you want to delete this item?")) {
            return $q(function (resolve, reject) {
                $rootScope.$broadcast('loaderStart', {});
                var url = app.root + '/Api/' + params.entityName + '/Delete';
                $http.post(url, entity).success(function (result) {
                    $rootScope.$broadcast('loaderEnd', {});
                    growl.addSuccessMessage('Item deleted');
                    resolve(result);
                });
            })
        }
    }

}]);

app.ng.service("urls", [function () {
    this.root = function () {
        return app.root;
    };

    this.integration = {
        synchKobo: function (projectId) {
            return app.root + '/Api/Import/UpdateCollectedData?projectId=' + projectId;
        }
    }

    // URLS
    this.document = {
        viewImage: function (id) {
            return app.root + "/Document/ViewImage/" + id;
        },
        download: function (id) {
            return app.root + "/Document/Download/" + id;
        },
        upload: function () {
            return app.root + "/Document/Upload";
        },
        api: {
            getForProcess: function (processId) {
                return app.root + "/Api/Document/GetForProcess?processId=" + processId;
            },
            getPublishedForProcess: function (processId) {
                return app.root + "/Api/Document/GetPublishedForProcess?processId=" + processId;
            },
            update: function () {
                return app.root + "/Api/Document/Update";
            },
            delete: function (id) {
                return app.root + "/Api/Document/Delete";
            }
        }
    }

    this.user = {
        api: {
            invite: function () {
                return app.root + "/Api/User/Invite";
            },
            checkEmailExists: function () {
                return app.root + "/Api/User/CheckEmailExists";
            },
            getPendingInvitations: function (orgId) {
                return app.root + "/Api/User/GetPendingInvitations?orgId=" + orgId;
            },
            getAll: function () {
                return app.root + "/Api/User/All";
            },
            get: function (id) {
                return app.root + "/Api/User/" + id;
            },
            getActivityData: function (id) {
                return app.root + "/Api/User/ActivityData?userId=" + id;
            },
            search: function () {
                return app.root + "/Api/User/Search";
            },
            searchInvites: function () {
                return app.root + "/Api/User/SearchInvites";
            },
            acceptInvite: function () {
                return app.root + "/Api/User/AcceptInvite";
            },
            rejectInvite: function () {
                return app.root + "/Api/User/RejectInvite";
            },
            activate: function () {
                return app.root + "/Api/User/Activate";
            },
            deactivate: function () {
                return app.root + "/Api/User/Deactivate";
			},
			reactivate: function () {
	            return app.root + "/Api/User/Reactivate";
            },
            update: function () {
                return app.root + "/Api/User/Update";
			},
            searchPendingUsers: function () {
				return app.root + "/Api/User/SearchPendingUsers";
			},
            updatePreferredLanguage: function () {
				return app.root + "/Api/User/UpdatePreferredLanguage";
			},
            getPreferredLanguage: function () {
	            return app.root + "/Api/User/GetPreferredLanguage";
            }
        }
    }

    this.content = {
        api: {
            get: function (id) {
                return app.root + "/Api/Content/Get?activityId=" + id;
            },
            getForProcess: function (id) {
                return app.root + "/Api/Content/GetForProcess?processId=" + id;
            },
            getForActivity: function (id) {
                return app.root + "/Api/Content/GetForActivity?activityId=" + id;
            },
            getLatestForActivity: function (id) {
                return app.root + "/Api/Content/GetLatestForActivity?activityId=" + id;
            },
            getAll: function () {
                return app.root + "/Api/Content/All";
            },
            update: function () {
                return app.root + "/Api/Content/Update";
            },
            addVersion: function () {
                return app.root + "/Api/Content/AddVersion";
            },
            search: function (query) {
                return app.root + "/Api/Content/Search?q=" + query;
            }
        }
    }

    this.style = {
        api: {
            getByActivityId: function (id) {
                return app.root + "/Api/Style/GetByActivityId?activityId=" + id;
            },
            getByLinkId: function (id) {
                return app.root + "/Api/Style/GetByLinkId?linkId=" + id;
            },
            updateActivityStyle: function () {
                return app.root + "/Api/Style/UpdateActivityStyle";
            },
            updateLinkStyle: function () {
                return app.root + "/Api/Style/UpdateLinkStyle";
            }
        }
    }


    this.process = {
        view: function (id) {
            return app.root + "/#/Process/" + id;
        },
        api: {
            get: function (id) {
                return app.root + "/Api/Process/Get?processId=" + id;
            },
            getAll: function () {
                return app.root + "/Api/Process/All";
            },
            getAncestor: function (id) {
                return app.root + "/Api/Process/GetAncestor?processId=" + id;
            },
            update: function () {
                return app.root + "/Api/Process/Update";
            },
            createSubProcess: function () {
                return app.root + "/Api/Process/CreateSubProcess";
            },
            deleteActivity: function () {
                return app.root + "/Api/Process/DeleteActivity";
            }
        }
    }

    this.pageLoad = {
        api: {
            track: function (id) {
                return app.root + "/Api/PageLoad/Track";
            },
            search: function () {
                return app.root + "/Api/PageLoad/Search";
            }
        }
    }

}]);
(function () {
	function getCookie(name) {
		var value = "; " + document.cookie;
		var parts = value.split("; " + name + "=");
		if (parts.length === 2) {
			return parts.pop().split(";").shift();
		}

		return null;
	}
	app.ng.provider("appTranslator",
		[
			function () {
				this.$get = [
					"$translate", "$rootScope", "urls", "$http", "$cookies", function ($translate, $rootScope, urls, $http, $cookies) {
						function getCurrentLanguage() {
							const currentLang = $cookies.get("__APPLICATION_CURRENT_LANGUAGE");
							if (currentLang) {
								return currentLang;
							}
							if ($rootScope.loggedIn) {
								$rootScope.$broadcast('loaderStart', {});
								$http.get(urls.user.api.getPreferredLanguage()).success(function(result) {
									$rootScope.$broadcast('loaderEnd', {});
									$cookies.put("__APPLICATION_CURRENT_LANGUAGE", result);
									return result;
								});
							} 
							return "English";
						}

						function set(lang) {
							$cookies.put("__APPLICATION_CURRENT_LANGUAGE", lang);
							$translate.preferredLanguage(lang);
							$translate.use(lang);
						}
						return {
							set: set,
							init: function () {
								var lang = getCurrentLanguage();
								set(lang);
								setTimeout(function () { $translate.refresh(lang); }, 0);
							},
							getCurrentLanguage: getCurrentLanguage
						};
					}
				];
			}
		])
		.config([
			"$translateProvider",
			function ($translateProvider) {
				$translateProvider.useStaticFilesLoader({
					prefix: '/Translations/',
					suffix: '.json'
				});

				var language = getCookie("__APPLICATION_CURRENT_LANGUAGE") || "English";
				$translateProvider.preferredLanguage(language);

				$translateProvider
					.useSanitizeValueStrategy(null)
					.forceAsyncReload(true);
			}
		])
		.run([
			"$rootScope",
			"$translate",
			"appTranslator",
			function ($rootScope, $translate, appTranslator) {
				$rootScope.$on("$translatePartialLoaderStructureChanged",
					function (event, part) {
						$translate.refresh(appTranslator.getCurrentLanguage());
					});
				appTranslator.init();
			}
		]);
}());
