import { ApplicationContext, DataUnit } from "@sankhyalabs/core";
import DataBinder from "../DataBinder";
import { metadataTest } from "./resources/metadataTest";
describe('DataBinder', () => {
  let dataBinder;
  let dataUnit;
  beforeEach(() => {
    dataUnit = new DataUnit();
    dataUnit.metadata = metadataTest;
    dataUnit.addRecord();
    dataUnit.selectFirst();
    dataBinder = new DataBinder(dataUnit);
  });
  it('constructor', async () => {
    expect(dataBinder).toBeTruthy();
  });
  it('ApplicationContext should be filled', () => {
    const dataBindersByDataUnit = ApplicationContext.getContextValue("__DATABINDER_BY_DATAUNIT__") || new Map();
    expect(dataBindersByDataUnit.get(dataUnit.dataUnitId).length).toBeGreaterThan(0);
  });
  it('ApplicationContext should be filled with two binders', () => {
    new DataBinder(dataUnit);
    const dataBindersByDataUnit = ApplicationContext.getContextValue("__DATABINDER_BY_DATAUNIT__") || new Map();
    expect(dataBindersByDataUnit.get(dataUnit.dataUnitId).length).toBe(2);
  });
  it('should be invalid for empty fields', async () => {
    const isValid = await DataBinder.validateByDataunit(dataUnit);
    dataBinder['_recordValidatorProcessor'] = {
      validate: () => Promise.reject(),
    };
    expect(isValid).toBe(false);
  });
  it('should be valid for filled fields', async () => {
    await dataUnit.setFieldValue('NAME', 'João');
    dataBinder['_recordValidatorProcessor'] = {
      validate: () => Promise.resolve(),
    };
    const isValid = await DataBinder.validateByDataunit(dataUnit);
    expect(isValid).toBe(true);
  });
  it('should be remove dataBinder on disconnected', async () => {
    dataBinder.onDisconnectedCallback();
    const dataBindersByDataUnit = ApplicationContext.getContextValue("__DATABINDER_BY_DATAUNIT__") || new Map();
    expect(dataBindersByDataUnit.get(dataUnit.dataUnitId).length).toBe(0);
  });
  it('Should tell if has multiple values between fields', () => {
    dataBinder['_dataUnit'].getSelectionInfo = jest.fn().mockReturnValue({ records: mockRecords() });
    const hasMultiplesLabels = dataBinder['hasMultipleValuesBetweenRecords']('label');
    const hasMultiplesValues = dataBinder['hasMultipleValuesBetweenRecords']('value');
    expect(hasMultiplesLabels).toBe(false);
    expect(hasMultiplesValues).toBe(true);
  });
});
function mockRecords() {
  return [
    { label: 'label mocked', value: 'value mocked 1' },
    { label: 'label mocked', value: 'value mocked 2' },
    { label: 'label mocked', value: 'value mocked 3' },
  ];
}
