'use strict';

(function () {
  // Attestments Controller Spec
  describe('Attestments Controller Tests', function () {
    // Initialize global variables
    var AttestmentsController,
      scope,
      $httpBackend,
      $stateParams,
      $location,
      Authentication,
      Attestments,
      mockAttestment;

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_, _Authentication_, _Attestments_) {
      // Set a new global scope
      scope = $rootScope.$new();

      // Point global variables to injected services
      $stateParams = _$stateParams_;
      $httpBackend = _$httpBackend_;
      $location = _$location_;
      Authentication = _Authentication_;
      Attestments = _Attestments_;

      // create mock attestment
      mockAttestment = new Attestments({
        _id: '525a8422f6d0f87f0e407a33',
        title: 'An Attestment about MEAN',
        content: 'MEAN rocks!'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['user']
      };

      // Initialize the Attestments controller.
      AttestmentsController = $controller('AttestmentsController', {
        $scope: scope
      });
    }));

    it('$scope.find() should create an array with at least one attestment object fetched from XHR', inject(function (Attestments) {
      // Create a sample attestments array that includes the new attestment
      var sampleAttestments = [mockAttestment];

      // Set GET response
      $httpBackend.expectGET('api/attestments').respond(sampleAttestments);

      // Run controller functionality
      scope.find();
      $httpBackend.flush();

      // Test scope value
      expect(scope.attestments).toEqualData(sampleAttestments);
    }));

    it('$scope.findOne() should create an array with one attestment object fetched from XHR using a attestmentId URL parameter', inject(function (attestments) {
      // Set the URL parameter
      $stateParams.attestmentId = mockAttestment._id;

      // Set GET response
      $httpBackend.expectGET(/api\/attestments\/([0-9a-fA-F]{24})$/).respond(mockAttestment);

      // Run controller functionality
      scope.findOne();
      $httpBackend.flush();

      // Test scope value
      expect(scope.attestment).toEqualData(mockAttestment);
    }));

    describe('$scope.create()', function () {
      var sampleAttestmentPostData;

      beforeEach(function () {
        // Create a sample attestment object
        sampleAttestmentPostData = new Attestments({
          title: 'An attestment about MEAN',
          content: 'MEAN rocks!'
        });

        // Fixture mock form input values
        scope.title = 'An Attestment about MEAN';
        scope.content = 'MEAN rocks!';

        spyOn($location, 'path');
      });

      it('should send a POST request with the form input values and then locate to new object URL', inject(function (attestments) {
        // Set POST response
        $httpBackend.expectPOST('api/attestments', sampleAttestmentPostData).respond(mockAttestment);

        // Run controller functionality
        scope.create(true);
        $httpBackend.flush();

        // Test form inputs are reset
        expect(scope.title).toEqual('');
        expect(scope.content).toEqual('');

        // Test URL redirection after the attestment was created
        expect($location.path.calls.mostRecent().args[0]).toBe('attestments/' + mockAttestment._id);
      }));

      it('should set scope.error if save error', function () {
        var errorMessage = 'this is an error message';
        $httpBackend.expectPOST('api/attestments', sampleAttestmentPostData).respond(400, {
          message: errorMessage
        });

        scope.create(true);
        $httpBackend.flush();

        expect(scope.error).toBe(errorMessage);
      });
    });

    describe('$scope.update()', function () {
      beforeEach(function () {
        // Mock attestment in scope
        scope.attestment = mockAttestment;
      });

      it('should update a valid attestment', inject(function (Attestments) {
        // Set PUT response
        $httpBackend.expectPUT(/api\/attestments\/([0-9a-fA-F]{24})$/).respond();

        // Run controller functionality
        scope.update(true);
        $httpBackend.flush();

        // Test URL location to new object
        expect($location.path()).toBe('/attestments/' + mockAttestment._id);
      }));

      it('should set scope.error to error response message', inject(function (Attestments) {
        var errorMessage = 'error';
        $httpBackend.expectPUT(/api\/attestments\/([0-9a-fA-F]{24})$/).respond(400, {
          message: errorMessage
        });

        scope.update(true);
        $httpBackend.flush();

        expect(scope.error).toBe(errorMessage);
      }));
    });

    describe('$scope.remove(attestment)', function () {
      beforeEach(function () {
        // Create new attestments array and include the attestment
        scope.attestments = [mockAttestment, {}];

        // Set expected DELETE response
        $httpBackend.expectDELETE(/api\/attestments\/([0-9a-fA-F]{24})$/).respond(204);

        // Run controller functionality
        scope.remove(mockAttestment);
      });

      it('should send a DELETE request with a valid attestmentId and remove the attestment from the scope', inject(function (attestments) {
        expect(scope.attestments.length).toBe(1);
      }));
    });

    describe('scope.remove()', function () {
      beforeEach(function () {
        spyOn($location, 'path');
        scope.attestment = mockAttestment;

        $httpBackend.expectDELETE(/api\/attestments\/([0-9a-fA-F]{24})$/).respond(204);

        scope.remove();
        $httpBackend.flush();
      });

      it('should redirect to attestments', function () {
        expect($location.path).toHaveBeenCalledWith('attestments');
      });
    });
  });
}());
