'use strict';

angular
  .module('oauth3', [])
  .service('Oauth3', [
    '$timeout'
  , '$q'
  , '$http'
  , function Oauth3($timeout, $q, $http) {

    var oauth3 = window.OAUTH3;

    // We need to make angular's $q appear to be a standard Promise/A+
    // fortunately, this is pretty easy
    // TODO don't use `new`, use a create function instead
    function PromiseAngularQ(fn) {
      var me = this;
      var d = $q.defer();

      $timeout(function () {
        fn(d.resolve, d.reject);
      }, 0);

      //this.then = d.promise.then;
      //this.catch = d.promise.catch;
      me.then = function (fn) {
        return d.promise.then(fn);
      };
      me.catch = function (fn) {
        return d.promise.catch(fn);
      };
      // return d.promise;
    }
    PromiseAngularQ.create = function (fn) {
      var d = $q.defer();
      $timeout(function () {
        fn(d.resolve, d.reject);
      }, 0);
      return d.promise;
    };


    //PromiseAngularQ.create = PromiseAngularQ;
    PromiseAngularQ.resolve = function (dataOrPromise) {
      return $q.when(dataOrPromise);
    };
    PromiseAngularQ.reject = function (errOrPromise) {
      return $q.reject(errOrPromise);
    };
    PromiseAngularQ.all = function (arr) {
      return $q.all(arr);
    };

    oauth3.providePromise(PromiseAngularQ).then(function () {
      // ignore
    }, function (/*err*/) {
      console.error("Bad Promise Implementation!");
    });

    oauth3.provideRequest($http);

    window.ngOauth3 = oauth3;

    return oauth3;
  }]);
