/**
 * Simple directive to display table rows.
 * Removes the need for ng-repeat to just display data.
 */
angular.module('tableDirectiveModule', [])
.directive('trRows', ['$compile', function ($compile) {
    return {
        restrict: 'EA',
        template: '',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch('rowdata', function() {
                var html = '';
                angular.forEach(scope.rowdata, function(tr, trkey) {
                    html += '<tr>';
                    angular.forEach(tr, function(td, tdkey){

                        if (td === null ) {
                            td = '<i class="muted">(Not reported)</i>'
                        }

                        if (td === '') {
                            td = '<i class="muted">(Empty)</i>'
                        }

                        // match a valid url (https://ihateregex.io/expr/url/) and replace with a link
                        const urlReg = new RegExp(
                            /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\+.~#?&\/\/=]*)$/i
                        );
                        if (urlReg.test(td)) {
                            td = `<a target="_blank" href="${td}">${td}</a>`;
                        }

                        let icon = '';
                        if (scope.highlight !== undefined && Object.keys(scope.highlight).length > 0) {
                            Object.keys(scope.highlight).forEach(item => {
                                if (td === item) {
                                    switch (scope.highlight[item]) {
                                        case 'green':
                                            icon = '<i class="green margin-right-small icon-ok-sign"></i>';
                                            break;
                                        case 'red':
                                            icon = '<i class="red margin-right-small icon-warning-sign"></i>';
                                            break;
                                    }
                                }
                            });
                        }

                        if (scope.tablehead != undefined && scope.tablehead[tdkey]) {
                            html += `<td class="${scope.tablehead[tdkey].type || ''}"><div>${icon} ${td}</div></td>`;
                        } else {
                            html += '<td><div>'+ icon + td +'</div></td>';
                        }

                    });
                    html += '</tr>';
                });
                // html may contain directives, should be compiled
                let linkFn = $compile(html);
                let content = linkFn(scope);
                element.html(content);
            });
        },
        scope: {
            rowdata: '=',
            tablehead: '=',
            highlight: '='
        }
    };
}]);