import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import { TOC_ATTRIBUTES, TOC_COMMAND, normalizeHeadingOptions } from './utils';
import TableOfContentsCommand from './tableofcontentscommand';
import '../../themes/styles/heading.css';

export default class TableOfContentsEditing extends Plugin {
    static get pluginName() {
		return 'TableOfContentsEditing';
	} 

    init() {
        const editor = this.editor;
        const model =  editor.model;
        const supportedHeadings = normalizeHeadingOptions(editor.config.get('tableOfContents.supportedHeadings'));
        model.schema.extend('$block', { allowAttributes: TOC_ATTRIBUTES.HEADING_CLASS } );
        model.schema.setAttributeProperties(TOC_ATTRIBUTES.HEADING_CLASS, { isFormatting: true } );
        editor.conversion.attributeToAttribute(buildClassDefinition(supportedHeadings));
        editor.commands.add(TOC_COMMAND, new TableOfContentsCommand(editor));
    }
}

function buildClassDefinition( supportedHeadings ) {
    const options = [];
    supportedHeadings.forEach((name) =>{
		try{
			/* Reference to the default config of the heading plugin
			editor.config.define( 'heading', {
				options: [
					{ model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
					{ model: 'heading1', view: 'h2', title: 'Heading 1', class: 'ck-heading_heading1' },
					{ model: 'heading2', view: 'h3', title: 'Heading 2', class: 'ck-heading_heading2' },
					{ model: 'heading3', view: 'h4', title: 'Heading 3', class: 'ck-heading_heading3' }
				]
			}); */
			const level = parseInt(name.replace('heading', '')) + 1;
			const className = 'h' + level;
			options.push({ name, className });
		}
		catch{

		}
    });

	const definition = {
		model: {
			key: TOC_ATTRIBUTES.HEADING_CLASS,
			values: options.map(option => option.name)
		},
		view: {}
	};

	for (const option of options) {
		definition.view[option.name] = {
			key: 'class',
			value: option.className
		};
	}
	return definition;
}
