/* Copyright CloudLinux Zug GmbH 2010-2017 All Rights Reserved
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 */

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { Helper } from '../helper';

@Pipe({
    name: 'highlight'
})
export class HighlightSearch implements PipeTransform {
    constructor(private sanitizer: DomSanitizer){}

    transform(value: any, text: any, count: number): any {
        text = String(text);
        if (!text || text.length < count) {
            return value;
        }
        // Match in a case insensitive maneer
        let re: RegExp;
        try {
            re = new RegExp(Helper.convertStringToHexRepresentation(text), 'gi');
        } catch (e) {
            return value;
        }

        const match = value.match(re);

        // If there's no match, just return the original value.
        if (!match) {
            return value;
        }

        const result = value.replace(re, '<mark>' + match[0] + '</mark>');
        return this.sanitizer.bypassSecurityTrustHtml(result);
    }
}
