/*
 * Copyright (c) 2015-2018 Red Hat, Inc.
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
'use strict';
import {CheHttpBackend} from '../api/test/che-http-backend';

/**
 * Test the custom validation directive
 * @author Oleksii Kurinnyi
 */

describe('custom-validator', () => {
  let $scope, form, $compile;

  /**
   * Backend for handling http operations
   */
  let httpBackend;

  beforeEach(angular.mock.module('userDashboard'));

  beforeEach(inject((_$compile_: ng.ICompileService, $rootScope: ng.IRootScopeService, cheHttpBackend: CheHttpBackend) => {
    $scope = $rootScope;
    $compile = _$compile_;

    httpBackend = cheHttpBackend.getHttpBackend();
    // avoid tracking requests from branding controller
    httpBackend.whenGET(/.*/).respond(200, '');
    httpBackend.when('OPTIONS', '/api/').respond({});

    $scope.validateFn = (value: number) => {
      return value % 2 === 0;
    };
  }));

  it('should make form invalid if value isn\'t valid', () => {
    let nonValidValue = 5;
    $scope.model = {value: ''};

    let element = angular.element(
      '<form name="form">' +
      '<input ng-model="model.value" name="value" custom-validator="validateFn($value)" />' +
      '</form>'
    );
    $compile(element)($scope);

    form = $scope.form;
    form.value.$setViewValue(nonValidValue);

    // check form (expect invalid)
    expect(form.value.$invalid).toBe(true);
    expect(form.value.$valid).toBe(false);
  });

  it('should leave form valid for valid value', () => {
    let newValidValue = 10;
    $scope.model = {value: ''};

    let element = angular.element(
      '<form name="form">' +
      '<input ng-model="model.value" name="value" custom-validator="validateFn($value)" />' +
      '</form>'
    );
    $compile(element)($scope);

    form = $scope.form;
    form.value.$setViewValue(newValidValue);

    // check form (expect valid)
    expect(form.value.$invalid).toBe(false);
    expect(form.value.$valid).toBe(true);
  });
});
