/*
 * Copyright (C) 2018, 2019 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {SCThings, SCThingType} from '@openstapps/core';
import {Validator} from '@openstapps/core-tools';
import {expect} from 'chai';
import path from 'path';
import {MinimalConnector} from '../src/minimal-connector.js';
import * as url from 'url';

/**
 * Gets the `SCThingType`-key as string
 *
 * @param instance Contains `type` with the value of a SCThingType-key
 */
function getSchemaNameFromType<T extends SCThings>(instance: T): string {
  const type = instance.type;
  const index = Object.values(SCThingType).indexOf(type);
  const key = Object.keys(SCThingType)[index];
  return `SC${key}`;
}

describe('minimal-connector', function () {
  let connector: MinimalConnector;
  let validator: Validator;

  beforeEach(async function () {
    validator = new Validator();
    await validator.addSchemas(
      path.join(
        path.dirname(url.fileURLToPath(import.meta.url)),
        '..',
        'node_modules',
        '@openstapps',
        'core',
        'lib',
        'schema',
      ),
    );
    connector = new MinimalConnector('f-u', 'minimal-connector');
  });

  it('should get sample things', async function () {
    for (const thing of await connector.getItems()) {
      const schemaName = getSchemaNameFromType(thing);
      // validate thing
      const validatorResult = validator.validate(thing, schemaName);
      expect(validatorResult.errors).to.have.lengthOf(
        0,
        JSON.stringify({
          errors: validatorResult.errors,
          thing: thing,
        }),
      );
    }
  });
});
