
import { marked } from 'marked';
import { ParsedAttributes, parse_attributes } from './attrs';
import { MarkdownOptions } from './render';

// todo: deprecate this

export interface BreadcrumbNavToken extends marked.Tokens.Generic {
	text: string;
	attrs: ParsedAttributes;
	items: marked.Token[][];
}

export function breadcrumb_nav_ext(renderer: marked.Renderer, opts: MarkdownOptions) : marked.TokenizerExtension & marked.RendererExtension {
	return {
		name: 'breadcrumb_nav',
		level: 'block',
		start: (src) => src.match(/^\/\/\//)?.index,
		tokenizer(src, tokens) {
			const rule = /^\/\/\/(\/*)([^\n]+)?(?:\n)((?:[^\/]|\/\/?(?!\/\1))+)\/\/\/\1/;
			const match = rule.exec(src);

			if (match) {
				const token: BreadcrumbNavToken = {
					type: 'breadcrumb_nav',
					raw: match[0],
					text: match[3],
					attrs: parse_attributes(match[2] || ''),
					tokens: [ ],
					items: [ ],
				};

				const lines = match[3].trim().split('\n');

				for (const line of lines) {
					const tokens = this.lexer.inlineTokens(line, [ ]);
					token.tokens.push(...tokens);
					token.items.push(tokens);
				}

				return token;
			}
		},
		renderer(token: BreadcrumbNavToken) {
			return `<nav aria-label="breadcrumbs" ${token.attrs.html_attrs.join(' ')}>\n`
				+ `\t<ol>\n`
				+ '\t\t'
					+ token.items.map((tokens, index) =>{ 
						let item = '<li>\n';

						if (index) {
							item += '\t\t\t<span class="separator" aria-hidden="true">/</span>\n';
						}

						item += `\t\t\t${this.parser.parseInline(tokens, renderer)}\n`;

						return item + '\t\t</li>';
					}).join('\n\t\t')
				+ '\n'
				+ `\t</ol>\n`
				+ `</nav>`;
		}
	};
}
