/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

const fs = require( 'fs' );
const upath = require( 'upath' );
const { globSync } = require( 'glob' );
const cheerio = require( 'cheerio' );

const SDK_SELECTOR = 'meta[name="sdk-samples"]';

module.exports = sourcePath => {
	const files = [];
	const filePaths = globSync( upath.join( sourcePath, '*.html' ) ).map( path => upath.normalize( path ) );

	for ( const filePath of filePaths ) {
		const content = fs.readFileSync( filePath, { encoding: 'utf8' } );
		const $ = cheerio.load( content, null, false );
		const samplesNames = $( SDK_SELECTOR ).attr( 'content' ) ? $( SDK_SELECTOR ).attr( 'content' ).split( '|' ) : null;
		const samples = samplesNames ? [] : null;
		const meta = {};

		if ( samplesNames ) {
			for ( const sample of samplesNames.entries() ) {
				const bodyItems = [];
				const headItems = [];
				const flags = {};
				$( `[data-sample*="${ sample[ 0 ] + 1 }"]` ).map( ( i, el ) => {
					const element = $( el ).clone();
					const ret = {};
					const outputArray = $( el ).parents( 'head' ).length ? headItems : bodyItems;

					if ( $( el ).is( '[type=template]' ) ) {
						// Template code support
						outputArray.push( {
							source: $( el ).text().replace( /&lt;/g, '<' ).replace( /&gt;/g, '>' )
						} );
					} else {
						if ( element.is( '[data-sample-short]' ) ) {
							element.text( '{%SHORT_EDITOR_CONTENT%}' );
							ret.short = true;
						}
						if ( element.is( '[data-sample-preserveWhitespace]' ) || element.is( '[data-sample-preserve-whitespace]' ) ) {
							ret.preserveWhitespace = true;
						}
						if ( element.is( '[data-sample-template]' ) && !flags.template ) {
							flags.template = element.data( 'sample-template' );
						}
						if ( element.is( '[data-sample-highlighter]' ) && !flags.highlighter ) {
							flags.highlighter = element.data( 'sample-highlighter' );
						}

						if ( element.is( '[data-sample-strip-outer-tag]' ) ) {
							ret.source = element.html().replace( /^\n|\n$/g, '' );
						} else {
							ret.source = $.html( element ).replace( /\s?data-sample(-[\w-]+)?="[^"]*?"/g, '' ); // Strip data attributes
						}

						outputArray.push( ret );
					}
				} );

				samples.push( {
					name: sample[ 1 ],
					bodyItems,
					headItems,
					flags
				} );
			}
		}

		$( 'meta[name^="sdk-"]' ).map( ( i, el ) => {
			const keyName = $( el ).attr( 'name' ).replace( 'sdk-', '' );

			meta[ keyName ] = $( el ).attr( 'content' );
		} );

		files.push( {
			name: upath.basename( filePath, '.html' ),
			description: $( 'meta[name="description"]' ).attr( 'content' ),
			title: $( 'title' ).text(),
			content: $( '.sdk-contents' ).html(),
			source: $.html(),
			path: upath.relative( sourcePath, filePath ),
			presetVersion: $( '.sdk-contents' ).data( 'cke-preset' ),
			sdkSamples: samples,
			meta
		} );
	}
	return files;
};
