const schema = require('./data/eds-c-card.schema.json');
const dataAttributesSchema = require('../eds-c-data-attributes/data/eds-c-data-attributes.schema.json');
const exampleJson = require('./data/eds-c-card.example.json');
const fs = require('fs');
const path = require('path');
const partialsDir = __dirname;
const filenames = fs.readdirSync(partialsDir);
const componentTemplate = fs.readFileSync(path.resolve(__dirname, 'eds-c-card.hbs'), 'utf8');
const cardBody = fs.readFileSync(path.resolve(`${__dirname}/partials/`, 'eds-c-cardBody.hbs'), 'utf8');
const handlebars = require('handlebars');
const {validateSchema} = require('../../development/tests/validate-schema.js');

// register the partials that are used inside the component main template
handlebars.registerPartial('eds-c-cardBody', cardBody);

const {findTemplates} = require('../../development/tests/templateLoader.js');
findTemplates(['eds-c-card', 'eds-c-data-attributes']).load(handlebars);

filenames.forEach(function (filename) {
    var matches = /^([^.]+).hbs$/.exec(filename);
    if (!matches) {
        return;
    }
    var name = matches[1];
    var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
    handlebars.registerPartial(name, template);
});

const componentHbs = handlebars.compile(componentTemplate);
const renderedComponent = componentHbs(exampleJson);

describe('EDS Component Card', () => {
    test('docs file exists', () => {
        const exists = fs.existsSync(path.resolve(__dirname, 'docs.md'));
        expect(exists).toBe(true);
    });
});

describe('Card Schema Validation and Accessibility Test', () => {
    const { configureAxe, toHaveNoViolations } = require('jest-axe');
    expect.extend(toHaveNoViolations);
    
    const axe = configureAxe({
        rules: {
            region: { enabled: false }
        }
    });

    test('Example data matches schema', () => {
        const valid = validateSchema(schema, exampleJson, [
            { name: 'eds-c-data-attributes', schema: dataAttributesSchema }
        ]);
        expect(valid).toBeTruthy();
    });

    test('Template can be compiled and rendered', () => {
        document.body.innerHTML = renderedComponent;
        const container = document.querySelector('*');
        expect(container).not.toBeNull();
    });
    
    test('Template passes basic HTML accessibility', async () => {
        expect(await axe(renderedComponent)).toHaveNoViolations();
    });
});