'use strict';

var angular = require('camunda-bpm-sdk-js/vendor/angular');
var CamSDK = require('camunda-bpm-sdk-js/lib/angularjs/index');

module.exports = ['$rootScope', '$timeout' , '$q', function($rootScope, $timeout, $q) {

  function AngularClient(config) {
    this._wrapped = new CamSDK.Client.HttpClient(config);
  }

  angular.forEach(['post', 'get', 'load', 'put', 'del', 'options', 'head'], function(name) {
    AngularClient.prototype[name] = function(path, options) {
      var myTimeout = $timeout(function() {}, 100000);

      var original = angular.isFunction(options.done) ? options.done : angular.noop;

      options.done = function(err, result) {

        function applyResponse() {
            // in case the session expired
          if (err && err.status === 401) {
              // broadcast that the authentication changed
            $rootScope.$broadcast('authentication.changed', null);
              // set authentication to null
            $rootScope.authentication = null;
              // broadcast event that a login is required
              // proceeds a redirect to /login
            $rootScope.$broadcast('authentication.login.required');
            return;
          }

          original(err, result);
        }

        var phase = $rootScope.$$phase;

        if(phase !== '$apply' && phase !== '$digest') {
          $rootScope.$apply(applyResponse);
        }
        else {
          applyResponse();
        }
        $timeout.cancel(myTimeout);
      };

      return $q.when(
        this._wrapped[name](path, options)
      );
    };
  });

  angular.forEach(['on', 'once', 'off', 'trigger'], function(name) {
    AngularClient.prototype[name] = function() {
      this._wrapped[name].apply(this, arguments);
    };
  });

  return AngularClient;
}];

@@ -222,16 +222,886 @@
  $q) %7B%0A%0A
+  var lastCookies = %7B%7D;%0A  var lastCookieString = '';%0A%0A  function cookies() %7B%0A    if (document && document.cookie !== lastCookieString) %7B%0A      lastCookieString = document.cookie;%0A      lastCookies = %7B%7D;%0A%0A      var cookieArray = lastCookieString.split('; ');%0A%0A      for (var i = 0; i %3C cookieArray.length; i++) %7B%0A        var cookie = cookieArray%5Bi%5D;%0A        var index = cookie.indexOf('=');%0A%0A        if (index %3E 0) %7B%0A          var name = unescape(cookie.substring(0, index));%0A          if (lastCookies%5Bname%5D === undefined) %7B%0A            lastCookies%5Bname%5D = unescape(cookie.substring(index + 1));%0A          %7D%0A        %7D%0A      %7D%0A    %7D%0A%0A    return lastCookies;%0A  %7D%0A%0A  function setHeaders(options) %7B%0A    var headers = options.headers = options.headers %7C%7C %7B%7D;%0A    var token = (cookies() %7C%7C %7B%7D)%5B'XSRF-TOKEN'%5D;%0A%0A    if (token) %7B%0A      headers%5B'X-XSRF-TOKEN'%5D = token;%0A    %7D%0A  %7D%0A%0A
   functi
@@ -1397,24 +1397,52 @@
 , 100000);%0A%0A
+      setHeaders(options);%0A%0A
       var or

set csrf request header