import Ajv from 'ajv';

import common from './common.json';
import dataformat from './dataformat.json';
import database from './database.json';
import library from './library.json';
// the `algorithm.json` schema is deprecated in favor of mirroring
// the file structure in beat.core
//import algorithm from './algorithm.json';
import algorithm1 from './algorithm_1.json';
import algorithm2 from './algorithm_2.json';
import algorithm3 from './algorithm_3.json';
import algorithm_common from './algorithm_common.json';
import toolchain from './toolchain.json';
import experiment from './experiment.json';
import execution from './execution.json';
import plotter from './plotter.json';
import plotterparameter from './plotterparameter.json';
import draft04 from 'ajv/lib/refs/json-schema-draft-04.json';

const ajv = new Ajv({ allErrors: true, schemaId: 'id' });
ajv.addMetaSchema(draft04);
ajv.addSchema([common, dataformat, database, library,
	// algorithm,
	algorithm1, algorithm2, algorithm3, algorithm_common,
	toolchain, experiment, plotter, plotterparameter, execution]);

export const VALIDATORS = {
	dataformat: ajv.compile(dataformat),
	database: ajv.compile(database),
	library: ajv.compile(library),
	algorithm: ajv.compile(algorithm3),
	toolchain: ajv.compile(toolchain),
	experiment: ajv.compile(experiment),
	plotter: ajv.compile(plotter),
	plotterparameter: ajv.compile(plotterparameter),
	execution: ajv.compile(execution),
};
Object.freeze(VALIDATORS);

export default function validate(validator, obj) {
	const isValid = validator(obj.contents || obj);
	const errs = validator.errors;
	/*
	if(!isValid) {
		console.error(`Object "${ obj.name || obj }" not valid!:`);
		console.log(obj);
		console.log(validator.errors);
	}
	*/

	return isValid ? false : errs;
}
