/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { CoreConfigurationLoaderService } from './core-configuration-loader.service';

describe('CoreConfigurationLoaderService', () => {
  let service: CoreConfigurationLoaderService;
  let httpTestingController: HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
    });
    service = TestBed.inject(CoreConfigurationLoaderService);
    httpTestingController = TestBed.inject(HttpTestingController);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should try to get file from url', fakeAsync(() => {
    const testUrl = '/assets/config.json';
    const mockResp = {
      environment: 'dev',
      endpointNavigation: 'foo',
    };
    let resp = null;

    service.load(testUrl).then((config) => (resp = config));
    const req = httpTestingController.expectOne(testUrl);
    expect(req.request.method).toEqual('GET');
    req.flush(mockResp);
    tick();

    expect(resp).toEqual(mockResp);

    expect(service.loadedConfig).toEqual(mockResp);
  }));

  it('should offer promise that is resolved when loaded', fakeAsync(() => {
    const testUrl = '/assets/config.json';
    const mockResp = {
      environment: 'dev',
      endpointNavigation: 'foo',
    };
    let resolvedConfig = null;

    service.config.then((config) => (resolvedConfig = config));
    expect(service.loadedConfig).toBeNull();

    service.load(testUrl);
    const req = httpTestingController.expectOne(testUrl);
    expect(req.request.method).toEqual('GET');
    req.flush(mockResp);
    tick();

    expect(resolvedConfig).toEqual(mockResp);
    expect(service.loadedConfig).toEqual(mockResp);
  }));

  it('should return an error when url is empty', () => {
    const testUrl = '';
    service.load(testUrl);
    const req = httpTestingController.expectOne(testUrl);
    req.flush('error', { status: 404, statusText: 'Not found' });
    expect(service.loadedConfig).toBeNull();
  });

  it('should not have config before loaded', fakeAsync(() => {
    expect(service.loadedConfig).toBeNull();
  }));

  afterEach(() => {
    // After every test, assert that there are no more pending requests.
    httpTestingController.verify();
  });
});
