'use strict';

angular.module('habitApp', ['ngSanitize'])
.config(['$compileProvider', function ($compileProvider) {
    //allow blob data in URLs
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|blob):/);
}])

.factory('taskFormatter', function() {
    var tf = {};

    var csvComponents = ['type', 'text', 'completed'];


    tf.csv = function(tasks) {
        var csv = '"' + csvComponents.join('","') + '"\n';

        for (var i=0; i<tasks.length; i++) {
            var t = tasks[i];
            var row = [];
            csvComponents.forEach( function(header) {
                row.push(t[header]);
            });
            csv += '"'+row.join('","') + '"\n';
        }

        return csv;
    };

    return tf;
})

.controller('habitExportCtrl', ['$scope', '$http', '$sce', 'taskFormatter', function ($scope,$http,$sce, formatter) {
    var rooturl = 'https://habitrpg.com:443/api/v2/';
    var MIME_TYPE = 'text/csv';

    var processFetch = function (tasks) {
        // The data returned is already parsed as JSON!
        $scope.csv = formatter.csv(tasks);
        
        //create download link
        var blob = new Blob([$scope.csv], { type: 'text/csv' });
        // clean up the old object
        if ($scope.csvURL) {
            window.URL.revokeObjectURL($scope.csvURL);
        }
        $scope.csvURL = (window.URL || window.webkitURL).createObjectURL(blob);
    };

    $scope.checkServer = function () {
        $http.get(rooturl + 'status').success(function(){$scope.msgEcho="server is there";})
    };

    $scope.fetchData = function () {
        var req = {
                method: 'GET',
                url: rooturl + 'user/tasks',
                headers: {
                'x-api-key': $scope.apiKey,
                'x-api-user': $scope.userId
                },
                data: {},
        };

        $http(req).success(processFetch).error(processFetch);
    };
    
    $scope.trust = function(s) {
        return $sce.trustAsHtml(s);
    };
}]);

@@ -751,80 +751,35 @@
 )%0A%0A.
-controller('habitExportCtrl', %5B'$scope', '$http', '$sce', 'taskFormatter
+factory('habitAPI', %5B'$http
 ', f
@@ -789,38 +789,14 @@
 tion
- 
 ($
-scope,$http,$sce, formatter
+http
 ) %7B%0A
@@ -849,24 +849,25 @@
 i/v2/';%0A
+%0A
     var 
 MIME_TYP
@@ -862,31 +862,659 @@
 var 
-MIME_TYPE = 'text/csv';
+api = %7B%7D;%0A    api.checkServer = function (callback) %7B%0A        $http.get(rooturl + 'status').success(callback);%0A    %7D;%0A%0A    api.fetchData = function (user, key, success, error) %7B%0A        var req = %7B%0A                method: 'GET',%0A                url: rooturl + 'user/tasks',%0A                headers: %7B%0A                'x-api-key': key, %0A                'x-api-user': user%0A                %7D,%0A                data: %7B%7D,%0A        %7D;%0A%0A        $http(req).success(success).error(error %7C%7C success);%0A    %7D;%0A%0A    return api;%0A%7D%5D)%0A%0A.controller('habitExportCtrl', %5B'$scope', '$sce', 'taskFormatter', 'habitAPI',%0A        function ($scope, $sce, formatter, habitrpg) %7B
 %0A%0A  
@@ -2025,72 +2025,67 @@
     
-$http.get(rooturl + 'status').success(function()%7B$scope.msgEcho=
+habitrpg.checkServer(function() %7B%0A            $scope.csv = 
 %22ser
@@ -2098,18 +2098,28 @@
  there%22;
+%0A        
 %7D)
+;
 %0A    %7D;%0A
@@ -2168,204 +2168,49 @@
     
-var req = %7B%0A                method: 'GET',%0A                url: rooturl + 'user/tasks',%0A                headers: %7B%0A                'x-api-key': $scope.apiKey,%0A                'x-api-
+habitrpg.fetchData($scope.
 user
-':
+Id,
  $scope.
 user
@@ -2209,119 +2209,16 @@
 ope.
-userId%0A                %7D,%0A                data: %7B%7D,%0A        %7D;%0A%0A        $http(req).success(processFetch).error(
+apiKey, 
 proc

Move the api calls into a service