const { Paper, Researcher, AssessmentResult, Assessment } = yoast.analysis;

export default class LocalTitleAssessment extends Assessment {
	constructor( settings ) {
		super();
		this.settings = settings;
	}

	/**
	 * Tests if the selected location is present in the title or headings.
	 *
	 * @param {Paper} paper The paper to run this assessment on.
	 * @param {Researcher} researcher The researcher used for the assessment.
	 * @param {Object} i18n The i18n-object used for parsing translations.
	 *
	 * @returns {object} an assessment result with the score and formatted text.
	 */
	getResult( paper, researcher, i18n ) {
		const assessmentResult = new AssessmentResult();
		if( this.settings.location !== '' ) {
			const businessCity = new RegExp( this.settings.location, 'ig');
			let matches = paper.getTitle().match( businessCity ) || 0;
			let result = this.scoreTitle( matches );

			// When no results, check for the location in h1 or h2 tags in the content.
			if( ! matches ) {
				const headings = new RegExp( '<h(1|2)>.*?' + this.settings.location + '.*?<\/h(1|2)>', 'ig' );
				matches = paper.getText().match( headings ) || 0;
				result = this.scoreHeadings( matches );
			}

			assessmentResult.setScore( result.score );
			assessmentResult.setText( result.text );
		}
		return assessmentResult;
	}

	/**
	 * Scores the url based on the matches of the location's city in the title.
	 *
	 * @param {Array} matches The matches in the video title.
	 *
	 * @returns {{score: number, text: *}} An object containing the score and text
	 */
	scoreTitle( matches ) {
		if ( matches.length > 0 ) {
			return {
				score: 9,
				text: this.settings.title_location
			}
		}
		return {
			score: 4,
			text: this.settings.title_no_location
		}
	}

	/**
	 * Scores the url based on the matches of the location's city in headings.
	 *
	 * @param {Array} matches The matches in the video title.
	 *
	 * @returns {{score: number, text: *}} An object containing the score and text
	 */
	scoreHeadings( matches ) {
		if ( matches.length > 0 ) {
			return{
				score: 9,
				text: this.settings.heading_location
			}
		}
		return{
			score: 4,
			text: this.settings.heading_no_location
		}
	}
}
