//import * from "dropDownClass.js";
var errorValidationMapObj;
class DynamicTabledata {

    bindTableBody(jsonData) {
        var tbodyRow = '';
        var jsonDataLength=jsonData.length;
        for (var index = 0; index < jsonDataLength; index++) {
            var bagroundColor = '';
            var duplicateKeyWord = '';
            errorValidationMapObj = new Map();
            errorValidationMapObj.set("rowIndex", index);//temp array
            this.checkForDuplicateSiteId(index,jsonDataLength, jsonData[index], jsonData[index + 1]);

            if (jsonData[index].duplicate == "true") {
                bagroundColor = 'bg-warning';
                duplicateKeyWord = '<br><span class="text-danger font-weight-bold">Dupliacte</span>';
            }
            tbodyRow += '<tr id="tableRowIndex_'+index+'" class="' + bagroundColor + '">' +
                '<td id="serialNumber' + index + '">' + (index + 1) + '</td>' +
                '<td>' + this.validateSiteId(jsonData[index].siteId, jsonData[index], "siteId") + duplicateKeyWord + '</td>' +
                '<td>' + this.validateSiteName(jsonData[index].siteName, jsonData[index], "siteName") + '</td>' +
                '<td>' + this.validateLatLng(jsonData[index], index, "LatLong") + '</td>' +
                '<td>' + this.getCustomerDropDown(jsonData[index].customerName, index, "cutomer") + '</td>' +
                '<td>' + this.getCircleDropDown(jsonData[index].circle, index, "circle") + '</td>' +
                '<td>' + this.checkForEmptyDistrict(jsonData[index].district)+ '</td>' +
                '</tr>';
            errorBucket.push(errorValidationMapObj);
        }
        return tbodyRow;
    }

/*
// dynamic heaading for excel
    bindTableHeader(jsonData) {
        // Function used to get all column names from JSON and bind the html table header
        var columnSet = [];
        var theadRow = '<tr>';
        for (var i = 0; i < jsonData.length; i++) {
            var rowHash = jsonData[i];
            for (var key in rowHash) {
                if (rowHash.hasOwnProperty(key)) {
                    if ($.inArray(key, columnSet) == -1) {
                        // Adding each unique column names to a variable array
                        columnSet.push(key);
                        if (key != 'latitude') {    
                            if (key == 'longitude') {
                                key = 'latitude & longitude';
                            }
                            theadRow += '<th class="'+key+'Th">' + key + '</th>';   
                        }else{
                            //skip latitude row because already marging in longitude. 
                        }
                    }
                }
            }
        }
        theadRow += "</tr>";
        return theadRow;
    }*/
    
     bindTableHeader(jsonData) {
        // Function used to get all column names from JSON and bind the html table header
        var columnSet = [];
        var theadRow = '<tr>'+
                        '<th class="snoTh">sno</th>'+
                        '<th class="siteIdTh">siteId</th>'+
                        '<th class="siteNameTh">siteName</th>'+
                        '<th class="latitude &amp; longitudeTh">latitude &amp; longitude</th>'+
                        '<th class="customerNameTh">customerName</th>'+
                        '<th class="circleTh">circle</th>'+
                        '<th class="districtTh">district</th>'+
                        '</tr>';
        return theadRow;
    }

    validateSiteId(data, jsonCurrentIndex, keyValue) {
        let maxSiteIdLength=30;
        let Indus_regex = /^IN-[0-9]{7}$/;// site id validation olny for indus site id.
        let space_regex = /^[^\s]+$/; // this regex expression is for finding the space between the siteId.
        let dropDownArray = getCustomerDropDownList();// array from constant.js
        if (data) {
            let siteId=data.replaceAll("'","");//trim the extra characters eg: '=>apostrophe
            
            if(jsonCurrentIndex.customerName.localeCompare(dropDownArray[0]) == 0){
                        if(!Indus_regex.test(siteId)){ 
                           errorValidationMapObj.set(keyValue, "Error");
                            return `${siteId}<br><span class="text-danger font-weight-bold">Invalid "IN-" followed by 7 digits</span>`; 
                        }
            }
            
            if(jsonCurrentIndex.customerName.localeCompare(dropDownArray[0])==0 || 
            jsonCurrentIndex.customerName.localeCompare(dropDownArray[1])==0  || 
            jsonCurrentIndex.customerName.localeCompare(dropDownArray[2])==0 || 
            jsonCurrentIndex.customerName.localeCompare(dropDownArray[6])==0)
            {
                        if(!space_regex.test(siteId)){
                          errorValidationMapObj.set(keyValue, "Error");
                            return `${siteId}<br><span class="text-danger font-weight-bold">Space Not allowed</span>`;   
                        }
            }
            
            
            
            
            if(siteId.length>maxSiteIdLength){
                errorValidationMapObj.set(keyValue, "Error");
                return `${siteId}<br><span class="text-danger font-weight-bold">Max 30 characters allowed</span>`;
            }else{
                errorValidationMapObj.set(keyValue, "noErrorFound");
                jsonCurrentIndex.siteId=siteId;// after replaced with (')update the  json
                return siteId;
            }
        } else {
            //console.log("jsonCurrentIndex" + jsonCurrentIndex);
            errorValidationMapObj.set(keyValue, "Error");
            return "<span class='text-danger font-weight-bold'>Required</span>";
        }
    }
    
    validateSiteName(data, jsonCurrentIndex, keyValue) {
        if (data) {
            errorValidationMapObj.set(keyValue, "noErrorFound");
            //trim the extra characters eg: '=>apostrophe
            let siteName=data.replaceAll("'","");
            jsonCurrentIndex.siteName=siteName;// after replaced with (') update the  json
            return siteName;
        } else {
           // console.log("jsonCurrentIndex" + jsonCurrentIndex);
            errorValidationMapObj.set(keyValue, "Error");
            return "<span class='text-danger font-weight-bold'>Required</span>";
        }
    }
    
    validateLatLng(rowData, index, keyValue) {
        var latitude = rowData.latitude;
        var longitude = rowData.longitude;
        const latLongPattern = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/;
        if (latitude && longitude) {// if latitude and longitude values are there 
            if (latLongPattern.test(latitude + ", " + longitude)) {
                errorValidationMapObj.set(keyValue, "noErrorFound");
                return latitude + "," + longitude;
            } else {
                errorValidationMapObj.set(keyValue, "Error");
                return "<span class='text-danger font-weight-bold'>invalid LAT-LONG<br><span class='text-dark'>(" + latitude + ", " + longitude + ")</span></span>";
            }
        } else {
            rowData.latitude = 0;
            rowData.longitude = 0
            return rowData.latitude + "," + rowData.longitude;
        }
    }

    getDynamicTableContent(jsonData) {
        var tableHeadContent = this.bindTableHeader(jsonData);
        var tableBodyContent = this.bindTableBody(jsonData);
        return "<thead>" + tableHeadContent + "</thead>" + "<tbody>" + tableBodyContent + "</tbody>";
    }

    getCustomerDropDown(customerValue, indexValue, keyValue) {
        var warningMessage;
        var error = true;
        var dropDownArray = getCustomerDropDownList();// array from constant.js
        var openSelectTag = '<select class="customerNameDropDown form-control" data-rowIndex="' + indexValue + '" data-colIndex="3" required>';
        var closedSelectTag = '</select>';
        var optionTags = '<option value="" disabled selected>Select CustomerName</option>';
        dropDownArray.forEach(function (customerNameInArray) {
            // console.log(customerNameInArray);
            if (customerNameInArray == customerValue) {
                optionTags += '<option value="' + customerNameInArray + '" selected>' + customerNameInArray + '</option>';
                error = false;
            } else {
                optionTags += '<option value="' + customerNameInArray + '">' + customerNameInArray + '</option>';
            }
        });
         var warningMessage=this.validateDropDownlist(customerValue,error,keyValue);
        return openSelectTag + optionTags + closedSelectTag + warningMessage;
    }    
    
    getCircleDropDown(circleValue, indexValue, keyValue) {
        var error = true;
        // errorBucket[indexValue]="select Circle Name from Dropdown List at S.No:"+indexValue;
        var dropDownArray = getCircleDropDownList();
        var openSelectTag = '<select class="circleDropDown form-control"  data-rowIndex="' + indexValue + '" data-colIndex="4"  required>';
        var closedSelectTag = '</select>';
        var optionTags = '<option class="bg-dark" selected="true" disabled="disabled" value="">Select Circle</option>';
        for (var loopCount = 0; loopCount < dropDownArray.length; loopCount++) {
            if (circleValue == dropDownArray[loopCount]) {
                optionTags += '<option value="' + dropDownArray[loopCount] + '" selected>' + dropDownArray[loopCount] + '</option>';
                error = false;
            } else {
                optionTags += '<option value="' + dropDownArray[loopCount] + '">' + dropDownArray[loopCount] + '</option>';
            }
        }
         var warningMessage=this.validateDropDownlist(circleValue,error,keyValue);
        return openSelectTag + optionTags + closedSelectTag + warningMessage;
    }
    
    validateDropDownlist(data,error,keyValue){
        var warningMessage;
        if (data) {
            if (error) {
                warningMessage = '<span class="text-danger font-weight-bold"> Value <span class="text-dark">(' + data + ')</span> is not in dropdown list</span>';
                errorValidationMapObj.set(keyValue, "Error");
            } else {
                errorValidationMapObj.set(keyValue, "noErrorFound");
                warningMessage = '';
            }
        } else { // if empty
            errorValidationMapObj.set(keyValue, "Error");
            warningMessage = '<span class="text-danger font-weight-bold">Please select '+keyValue+' from dropdown list</span>';
        }
        return warningMessage;
    }
    checkForEmptyDistrict(districtKeyWord){
        if(districtKeyWord){// if present
            
            return districtKeyWord;
        }else{
            return '--';
        }
        
    }
    
    checkForDuplicateSiteId(loopCount,jsonDataLength, curentJsonRow, nextJsonRow) {
        if ((loopCount + 1) < jsonDataLength) { // not to be out of bound
            if (curentJsonRow.siteId != null && nextJsonRow.siteId != null) { // not to be empty
                if (curentJsonRow.siteId == nextJsonRow.siteId) {
                    curentJsonRow.duplicate = "true";
                    nextJsonRow.duplicate = "true";
                }
            }
        }
    }


}


// ;;