'use strict';

(function () {
  // Attestations Controller Spec
  describe('Attestations Controller Tests', function () {
    // Initialize global variables
    var AttestationsController,
      scope,
      $httpBackend,
      $stateParams,
      $location,
      Authentication,
      Attestations,
      mockAttestation;

    // 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_, _Attestations_) {
      // Set a new global scope
      scope = $rootScope.$new();

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

      // create mock attestation
      mockAttestation = new Attestations({
        _id: '525a8422f6d0f87f0e407a33',
        title: 'An Attestation about MEAN',
        content: 'MEAN rocks!'
      });

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

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

    it('$scope.find() should create an array with at least one attestation object fetched from XHR', inject(function (Attestations) {
      // Create a sample attestations array that includes the new attestation
      var sampleAttestations = [mockAttestation];

      // Set GET response
      $httpBackend.expectGET('api/attestations').respond(sampleAttestations);

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

      // Test scope value
      expect(scope.attestations).toEqualData(sampleAttestations);
    }));

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

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

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

      // Test scope value
      expect(scope.attestation).toEqualData(mockAttestation);
    }));

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

      beforeEach(function () {
        // Create a sample attestation object
        sampleAttestationPostData = new Attestations({
          title: 'An Attestation about MEAN',
          content: 'MEAN rocks!'
        });

        // Fixture mock form input values
        scope.title = 'An Attestation 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 (Attestations) {
        // Set POST response
        $httpBackend.expectPOST('api/attestations', sampleAttestationPostData).respond(mockAttestation);

        // 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 attestation was created
        expect($location.path.calls.mostRecent().args[0]).toBe('attestations/' + mockAttestation._id);
      }));

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

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

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

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

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

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

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

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

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

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

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

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

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

      it('should send a DELETE request with a valid attestationId and remove the attestation from the scope', inject(function (Attestations) {
        expect(scope.attestations.length).toBe(1);
      }));
    });

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

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

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

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