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

'use strict';

const upath = require( 'upath' );
const shouldDisplayNewIndicator = require( '../../utils/shoulddisplaynewindicator' );
const getReportIssueWidgetUrl = require( '../../utils/getreportissuewidgeturl' );

/**
 * Adds project information (e.g. BASE_PATH, project name, group id) to each page.
 * This is the first filter run for each documentation page (except API docs).
 */
hexo.extend.filter.register( 'before_post_render', page => {
	const split = page.path.split( '/' );
	const projectName = split[ 0 ];

	page.canonicalUrlBeginning = hexo.projectGlobals.common.canonicalUrlBeginning || 'https://ckeditor.com/docs/';

	if ( !hexo.projectGlobals || !hexo.projectGlobals[ projectName ] ) {
		page.BASE_PATH = '.';

		return page;
	}

	const projectGlobals = hexo.projectGlobals[ projectName ];
	const projectCategories = projectGlobals.categoryIds;
	const basePath = projectGlobals.BASE_PATH;
	const category = projectCategories.get( page.category );

	page.BASE_PATH = basePath;
	page.projectName = projectName;
	page.projectfullname = projectGlobals.config.name;
	page.groupId = category ? category.groupId : null;
	page.groupSlug = category ? category.groupSlug : null;
	page.shortName = upath.basename( page.source ).replace( upath.extname( page.source ), '' );

	if ( projectGlobals.config.permalinkDisableDomains ) {
		page.permalinkDisableDomains = projectGlobals.config.permalinkDisableDomains.join( ',' );
	}

	if ( hexo.projectGlobals.common.isSingleProject && projectGlobals.config.canonicalUrlBeginning ) {
		page.canonicalUrlBeginning = projectGlobals.config.canonicalUrlBeginning;
	}

	page.shouldDisplayNewIndicator = shouldDisplayNewIndicator( page );

	// This line needs to be sync with the `src/api-builder/api-builder.js` file.
	page.reportIssueWidget = getReportIssueWidgetUrl( page, projectGlobals.config );

	return page;
}, 1 );

// The lower the priority the sooner a filter is executed.
