'use strict';

(function () {
  // FeatureMappers Controller Spec
  describe('FeatureMappers Controller Tests', function () {
    // Initialize global variables
    var FeatureMappersController,
      scope,
      $httpBackend,
      $stateParams,
      $location,
      Authentication,
      FeatureMappers,
      mockFeatureMapper;

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

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

      // create mock featureMapper
      mockFeatureMapper = new FeatureMappers({
        _id: '525a8422f6d0f87f0e407a33',
        title: 'An FeatureMapper about MEAN',
        content: 'MEAN rocks!'
      });

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

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

    it('$scope.find() should create an array with at least one featureMapper object fetched from XHR', inject(function (FeatureMappers) {
      // Create a sample featureMappers array that includes the new featureMapper
      var sampleFeatureMappers = [mockFeatureMapper];

      // Set GET response
      $httpBackend.expectGET('api/featureMappers').respond(sampleFeatureMappers);

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

      // Test scope value
      expect(scope.featureMappers).toEqualData(sampleFeatureMappers);
    }));

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

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

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

      // Test scope value
      expect(scope.featureMapper).toEqualData(mockFeatureMapper);
    }));

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

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

        // Fixture mock form input values
        scope.title = 'An FeatureMapper 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 (featureMappers) {
        // Set POST response
        $httpBackend.expectPOST('api/featureMappers', sampleFeatureMapperPostData).respond(mockFeatureMapper);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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