import RegexUtil from './RegexUtil';
import FlexPlayerUtil from './FlexPlayerUtil';

export default class TranscriptUtil {

	//TODO get the number of matches per segment as well!
	static calcTranscriptMatchesPerMediaObject = (mediaObjects, transcript, initialSearchTerm) => {
		if(!transcript || !initialSearchTerm) return {};

		const matches = {};
        let regex = null;
        try {
            regex = RegexUtil.generateRegexForSearchTerm(initialSearchTerm);
        } catch (err) {
            console.debug('invalid regex');
        }
        if (regex) {
            mediaObjects.forEach(mo => {
                matches[mo.assetId] = this.getTranscript(transcript, mo).reduce((acc, phrase) => {
                    return acc + (phrase.words.match(regex) || []).length;
                }, 0);
            });
        }
        return matches;
    };

    //takes into account the active carrier/track and whether it relates to off-air content or not
    static getTranscript = (transcript, currentMediaObject) => {
        if(!transcript || !currentMediaObject) return null;
        return transcript.filter(t => {
            //first make sure the transcript only includes the active carrier/track
            if(t.carrierId === currentMediaObject.assetId || t.carrierId === currentMediaObject.devientTranscriptId) {
                //then make sure the transcript does not contain off-air lines
                if(!FlexPlayerUtil.isTimeBeforeOnAir(t.start / 1000, currentMediaObject) &&
                    !FlexPlayerUtil.isTimeAfterOnAir(t.start / 1000, currentMediaObject)) {
                    return true
                }
            }
            return false
        })
    };
}