import { ChartjsChartComponent } from './chartjs-chart.component';
import * as helperFunctions from './chartjs-helper-functions';

describe('ChartJsContentComponent ', () => {
  let component: ChartjsChartComponent;
  const spyBarChart = jest.spyOn(helperFunctions, 'createBarChart').mockReturnValue({} as any);
  const spyLineChart = jest.spyOn(helperFunctions, 'createLineChart').mockReturnValue({} as any);

  beforeEach(() => {
    component = new ChartjsChartComponent();
    component.type = 'line';
    component.chartContainer = { nativeElement: {} };
  });

  afterEach(() => {
    // spyBarChart.mockClear();
    // spyLineChart.mockClear();
    jest.clearAllMocks();
  });

  it('should create a line chart', () => {
    component.ngOnInit();
    expect(component).toBeTruthy();
    expect(spyLineChart).toHaveBeenCalledTimes(1);
    expect(spyBarChart).toHaveBeenCalledTimes(0);
  });

  it('should create a bar chart', () => {
    component.type = 'bar';
    component.ngOnInit();
    expect(component).toBeTruthy();
    expect(spyLineChart).toHaveBeenCalledTimes(0);
    expect(spyBarChart).toHaveBeenCalledTimes(1);
  });

  it('should throw a error if not supported chart type', () => {
    const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation((message) => message);
    component.type = 'pie' as any;
    component.ngOnInit();
    expect(component).toBeTruthy();
    expect(spyLineChart).toHaveBeenCalledTimes(0);
    expect(spyBarChart).toHaveBeenCalledTimes(0);
    expect(consoleErrorSpy).toHaveBeenCalledWith('unfortunately bci-chartjs-chart does not support chartjs type pie');
  });

  it('should update chart if data has changed', () => {
    component['chart'] = { data: '', update: jest.fn() } as any;
    component.ngOnChanges({ data: { currentValue: 'testValue', previousValue: {} } } as any);
    expect(component['chart'].data).toEqual('testValue');
    expect(component['chart'].update).toHaveBeenCalledTimes(1);
  });

  it('should update chart config if config has changed', () => {
    component['chart'] = {
      update: jest.fn(),
      options: { isValid: false, plugins: { pluginC: 'testC' }, testProperty: 'testPropertyValue' }
    } as any;
    component.ngOnChanges({
      options: {
        currentValue: { plugins: { pluginA: 'testA', pluginB: 'testB' }, isValid: true },
        previousValue: {}
      }
    } as any);
    expect(component['chart'].options).toEqual({
      isValid: true,
      plugins: { pluginA: 'testA', pluginB: 'testB', pluginC: 'testC' },
      testProperty: 'testPropertyValue'
    });
    expect(component['chart'].update).toHaveBeenCalledTimes(1);
  });
});
