'use strict';

(function () {
  // HostNames Controller Spec
  describe('HostNames Controller Tests', function () {
    // Initialize global variables
    var HostNamesController,
      scope,
      $httpBackend,
      $stateParams,
      $location,
      Authentication,
      HostNames,
      mockHostName;

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

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

      // create mock hostName
      mockHostName = new HostNames({
        _id: '525a8422f6d0f87f0e407a33',
        title: 'An HostName about MEAN',
        content: 'MEAN rocks!'
      });

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

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

    it('$scope.find() should create an array with at least one hostName object fetched from XHR', inject(function (HostNames) {
      // Create a sample hostNames array that includes the new hostName
      var sampleHostNames = [mockHostName];

      // Set GET response
      $httpBackend.expectGET('api/hostNames').respond(sampleHostNames);

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

      // Test scope value
      expect(scope.hostNames).toEqualData(sampleHostNames);
    }));

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

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

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

      // Test scope value
      expect(scope.hostName).toEqualData(mockHostName);
    }));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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