import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
import tableIcon from '../../themes/icons/table-excel.svg';
import { TOC_COMMAND, normalizeHeadingOptions } from './utils';

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

    init() {
        const editor = this.editor;
        const t = editor.t;
        const supportedHeadings = normalizeHeadingOptions(editor.config.get('tableOfContents.supportedHeadings'));
        editor.ui.componentFactory.add('tableOfContents', locale => {
            const buttonView = new ButtonView( locale );
            buttonView.set( {
                label: t('Create Table of Contents'),
                icon: tableIcon,
                withText: false,
                tooltip: true
            } );
            
            // Bind button to the command.
            const tocCommand = editor.commands.get(TOC_COMMAND);
            buttonView.bind('isEnabled').to(tocCommand, 'isEnabled' );
            buttonView.bind('isOn').to(tocCommand, 'value', value => !!value );

            buttonView.on('execute', () => {
                editor.execute(TOC_COMMAND, { headings: supportedHeadings });
            });
            return buttonView;
        });
    }
} 