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

    bindTableBody(jsonData) {
        var tbodyRow = '';
        var jsonDataLength=jsonData.length;
        for (var index = 0; index < jsonDataLength; index++) {
            var backGroundColor = '';
            var duplicateKeyWord = '';
            var trUniqueClass=jsonData[index].siteId+"_"+this.getDate(jsonData[index]['siteVisitDate(yyyy-mm-dd)'])+"_"+this.getEmpId(jsonData[index].siteAssignedToEmpId);
            errorValidationMapObj = new Map();
            errorValidationMapObj.set("rowIndex", index);//temp array
            this.checkForDuplicateSiteIdPoDetails(index,jsonDataLength, jsonData[index], jsonData[index + 1]);
            this.checkRequiredCondition(index,jsonData[index]);
            jsonData[index].deleteReferenceId=index;// for deleting purpose reference Index
            if (jsonData[index].duplicate == true) {
                backGroundColor = 'bg-light-danger ';
                duplicateKeyWord = '<br><span class="text-danger font-weight-bold">Dupliacte</span>';
            }
            tbodyRow += '<tr id="tableRowIndex_'+index+'" class="' + backGroundColor + trUniqueClass+ '">' + // truinqueClass = siteId_siteVisitDate_empId
                '<td id="serialNumber' + index + '">' + (index + 1) + '</td>' +
                '<td class="siteId">' + this.validateSiteId(jsonData[index].siteId, jsonData[index], "siteId") + duplicateKeyWord + '</td>' +
                this.validateSiteName(jsonData[index].siteName, jsonData[index], jsonData[index].siteNameMismatch, "siteName") +
                this.validateLatLng(jsonData[index], index,jsonData[index].latitudeMismatch,jsonData[index].longitudeMismatch, "LatLong") +
                this.getCustomerDropDown(jsonData[index].customerName, index, jsonData[index].customerNameMismatch, "customer") +
                this.getCircleDropDown(jsonData[index].circle, index,jsonData[index].circleMismatch, "circle") +
                this.checkForEmptyDistrict(jsonData[index].district, jsonData[index].districtMismatch)+
                this.getPoNumber_Tds(jsonData[index].poNumber,jsonData[index],index, "poNumber")+
                this.getEmpIdName_Tds(jsonData[index], index, "empId") +
                this.getSiteVisitDate_Tds(jsonData[index]['siteVisitDate(yyyy-mm-dd)'], jsonData[index].requiredCondition,jsonData[index], index, "siteVisitDate")+
                this.getProject_stageOfAudit_Tds(jsonData[index].project, jsonData[index].stageOfAudit, jsonData[index].requiredCondition, index)+
                this.getOperationsTd(index)+
                '</tr>';
            errorBucket.push(errorValidationMapObj);
        }
        return tbodyRow;
    }

     bindTableHeader(jsonData) {
        // Function used to get all column names from JSON and bind the html table header
        var columnSet = [];
        var theadRow = '<tr><th colspan="7" class="text-center">Site Details</th><th colspan="6" class="text-center border-left">Employee Allocations</th></tr>'+
                        '<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>'+
                        '<th class="poNumberTh border-left">poNumber</th>'+
                        '<th class="empIdNameTh">empName(empId)</th>'+
                        '<th class="siteVisitDateTh">site Visit Date</th>'+
                        '<th class="projectTh">project</th>'+
                        '<th class="stageOfAuditTh">stage of Audit</th>'+
                        '<th class="operationTh px-4">Operations</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){
                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, siteNameMismatch, keyValue) {
        let checkMismatchedSitName=(siteName)=>{
            if(siteNameMismatch){
                return `<td class="misMatchError">${siteName}<span class="text-danger font-weight-bold d-block text-center">Mismatch</span></td>`;
            }else{
                return `<td>${siteName}</td>`;
            }
        }
        if(data) {
            errorValidationMapObj.set(keyValue, "noErrorFound");
            let siteName=data.replaceAll("'","");                               //trim the extra characters eg: '=>apostrophe
            jsonCurrentIndex.siteName=siteName;                                 // after replaced with (') update the  json
            return checkMismatchedSitName(siteName);
        } else {
            errorValidationMapObj.set(keyValue, "Error");
            return `<td><span class='text-danger font-weight-bold'>Required</span></td>`;
        }
    }
    
    validateLatLng(rowData, index,latMismatch, lngMismatch, keyValue) {
        let checkMismatchedLatLng=(latLng)=>{
            if(latMismatch || lngMismatch){
                return `<td class="misMatchError">${latLng}<span class="text-danger font-weight-bold d-block text-center">Mismatch</span></td>`;
            }else{
                return `<td>${latLng}</td>`;
            }
        }
        
        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 checkMismatchedLatLng(latitude + "," + longitude);
            } else {
                errorValidationMapObj.set(keyValue, "Error");
                return `<td><span class='text-danger font-weight-bold'>invalid LAT-LONG<br><span class='text-dark'>(${latitude},${longitude})</span></span></td>`;
            }
        } else {
            rowData.latitude = 0;
            rowData.longitude = 0
            return `<td>${rowData.latitude},${rowData.longitude}</td>`;
        }
    }
    
    getSiteVisitDate_Tds(siteVisitDate, requiredCondition, currentIndexJson, indexValue, keyValue){
        let uiContent;
        let dateReg1=/^\d{4}\/(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])$/; // for 2020/10/01
        let dateReg2=/^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/; // for 2021-10-10
        if(siteVisitDate){
            // console.log(siteVisitDate);
            if(siteVisitDate.match(dateReg1) || siteVisitDate.match(dateReg2)){                   // validate date with YYYY/MM/DD formate
                siteVisitDate=siteVisitDate.replaceAll('/','-');
                uiContent=`<td id="siteVisitDateTd_${indexValue}"><input type="date" class="form-control siteVisitDate" value="${siteVisitDate}" data-rowIndex="${indexValue}" /></td>`;
                currentIndexJson['siteVisitDate(yyyy-mm-dd)']=siteVisitDate;
                errorValidationMapObj.set(keyValue, "noErrorFound");
            }else{
                uiContent=`<td id="siteVisitDateTd_${indexValue}">(${siteVisitDate})<span class='text-danger font-weight-bold'>InValid Date formate</span></td>`;
                errorValidationMapObj.set(keyValue, "Error");
            }
        }else{
            if(requiredCondition){
                uiContent=`<td id="siteVisitDateTd_${indexValue}"><input type="date" class="form-control siteVisitDate" data-rowIndex="${indexValue}"/> <span class="text-danger font-weight-bold justify-content-center d-flex" style="">Required</span></td>`;
                errorValidationMapObj.set(keyValue, "Error")
            }else{
                uiContent=`<td id="siteVisitDateTd_${indexValue}" ><input type="date" class="form-control siteVisitDate bg-warning" data-rowIndex="${indexValue}"/></td>`;
                errorValidationMapObj.set(keyValue, "noErrorFound");
            }
        }
        return uiContent;
    }
    getPoNumber_Tds(poNumber, jsonCurrentIndex, indexValue, keyValue){
        if(poNumber && poNumber!="Not Available"){
            let updatedPoNumber=poNumber.replaceAll("'","");//trim the extra characters eg: '=>apostrophe
            jsonCurrentIndex.poNumber=updatedPoNumber;
            // errorValidationMapObj.set(keyValue, "noErrorFound");
            return `<td class="border-left">
                        <input type="text" value="${updatedPoNumber}" class="form-control poDropDownInputList" list="poDropDownList${indexValue}" placeholder="Enter PO Number"  data-rowIndex="${indexValue}"/>
                        <datalist id="poDropDownList${indexValue}">
                            <option>Not Available</option>
                        </datalist>
                    </td>`;
        }else{
            // errorValidationMapObj.set(keyValue, "Error");
            jsonCurrentIndex.poNumber="Not Available";
            return `<td class=" border-left">
                        <input type="text" value="Not Available" class="form-control poDropDownInputList bg-warning" list="poDropDownList${indexValue}" placeholder="Enter PO Number" data-rowIndex="${indexValue}"/>
                        <datalist id="poDropDownList${indexValue}">
                            <option>Not Available</option>
                        </datalist>
                    </td>`;
        }
    }

    getEmpIdName_Tds(currentIndexJson, indexValue, keyValue){
            let empId=currentIndexJson.siteAssignedToEmpId;
            let requiredCondition=currentIndexJson.requiredCondition;
            let bgColor=(!empId && !requiredCondition) ? 'bg-warning':'';
            let error= true;
            let empName="--";
            let openSelectTag=`<select class="empIdDropDown form-control ${bgColor}" data-rowIndex=${indexValue}>`;
            let closedSelectTag=`</select>`;
            let optionTags=`<option value="" selected disabled>Select EmpId</option>`;
            let empIdNameArray = getLocalStorageValue("EMP_ID_NAME_ARRAY"); // fucntion call in main.js file
            empIdNameArray.forEach(function(loopObj){
                if(loopObj.empId==empId){
                    optionTags+=`<option value=${loopObj.empId} selected>${loopObj.empName}(${loopObj.empId})</option>`;
                    empName=loopObj.empName;
                    error=false;
                }else{
                    optionTags+=`<option value=${loopObj.empId}>${loopObj.empName}(${loopObj.empId})</option>`;
                }
            });
            currentIndexJson.siteAssignedToEmpName=empName;
            var warningMessage= requiredCondition ? this.validateDropDownlist(empId, error, keyValue):this.checkValueInDropDownList(empId, error, keyValue);
        return `<td id="empIdNameTd_${indexValue}">${openSelectTag+ optionTags +closedSelectTag+warningMessage}</td>`;
    }
    
    getProject_stageOfAudit_Tds(projectNameValue, stageOfAuditValue, requiredCondition, indexValue){
        let projectName=projectNameValue ? projectNameValue.toUpperCase():'';
        let stageOfAudit=stageOfAuditValue ? stageOfAuditValue.toUpperCase():'';
        let projectError=true;
        let bgColor=(!projectName && !requiredCondition) ? 'bg-warning':'';
        let projectSelectedName='';
        let projectDropDown=()=>{
            let openSelectTag=`<select class="projectDropDown form-control ${bgColor}" data-rowIndex=${indexValue}>`;
            let closedSelectTag=`</select>`;
            let optionTags=`<option value="" selected disabled>Select Project</option>`;
            let projectListArray=PROJECT_AND_STAGE_OF_AUDIT_DD.projectsList;                //PROJECT_AND_STAGE_OF_AUDIT_DD in main.js
            projectListArray.forEach(function(value){
                if(projectName==value){
                    optionTags+=`<option value='${value}' selected>${value}</option>`;
                    projectError=false;
                    projectSelectedName=value;
                }else{
                    optionTags+=`<option value='${value}'>${value}</option>`;
                }
            });
             var warningMessage= requiredCondition ? this.validateDropDownlist(projectName, projectError, "project") : this.checkValueInDropDownList(projectName, projectError, "project");
            return openSelectTag+optionTags+closedSelectTag+warningMessage;
        };
        
        let stageOfAuditDropdown=()=>{
            let error=true;
            let openSelectTag=`<select class="stageOfAuditDropDown form-control ${bgColor}" data-rowIndex=${indexValue}>`;
            let closedSelectTag=`</select>`;
            let optionTags=`<option value="" selected disabled>Select Stage Of Audit</option>`;
            let stageOfAuditListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[projectSelectedName];       //PROJECT_AND_STAGE_OF_AUDIT_DD in main.js
                if(stageOfAuditListArray){
                    stageOfAuditListArray.forEach(function(value){
                        if(stageOfAudit==value){
                            optionTags+=`<option value='${value}'' selected>${value}</option>`;
                            error=false;
                        }else{
                            optionTags+=`<option value='${value}'>${value}</option>`;
                        }
                    });
                }
            // let warningMessage=this.validateDropDownlist(stageOfAudit, error, "stageOfAudit");
            let warningMessage= requiredCondition ? this.validateStageOfAuditDropDownlist(projectError,stageOfAudit, error, "stageOfAudit") : this.checkValueInDropDownList(stageOfAudit, error, "stageOfAudit");
            return openSelectTag+optionTags+closedSelectTag+warningMessage;
        };
        
            return `<td id="projectTd_${indexValue}" >${projectDropDown()}</td>
                <td id="stageOfAuditTd_${indexValue}" >${stageOfAuditDropdown()}</td>`;
    }
    
    getDynamicTableContent(jsonData) {
        // console.log(jsonData);
        var tableHeadContent = this.bindTableHeader(jsonData);
        var tableBodyContent = this.bindTableBody(jsonData);
        return "<thead>" + tableHeadContent + "</thead>" + "<tbody>" + tableBodyContent + "</tbody>";
    }

    getCustomerDropDown(customerValue, indexValue, customerMisMatch,  keyValue) {
        let checkMismatchedCstName=(customerDropDown, message)=>{
            if(customerMisMatch && (message==='')){
                return `<td class="misMatchError">${customerDropDown}<span class="text-danger font-weight-bold d-block text-center">Mismatch</span></td>`;
            }else{
                return `<td>${customerDropDown+message}</td>`;
            }
        }
        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) {
                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 checkMismatchedCstName(openSelectTag + optionTags + closedSelectTag, warningMessage);
    }   
    
    getCircleDropDown(circleValue, indexValue, circleMismatch, keyValue) {
        let checkMismatchedCircle=(circleDropDown, message)=>{
            if(circleMismatch && (message==='')){
                return `<td class="misMatchError">${circleDropDown}<span class="text-danger font-weight-bold d-block text-center">Mismatch</span></td>`;
            }else{
                return `<td>${circleDropDown+message}</td>`;
            }
        }
        var error = true;
        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 checkMismatchedCircle(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;
    }
    
    checkValueInDropDownList(data, error, keyValue){
        let uiContent=``;
        if(data){
            uiContent=`<span class="text-danger font-weight-bold"> Value <span class="text-dark">(${data})</span> is not in dropdown list</span>`;
            errorValidationMapObj.set(keyValue, "Error");
        }
        if(error){
            return uiContent;
        }else{
            errorValidationMapObj.set(keyValue, "noErrorFound");
            return '';
        }
    }
    
    validateStageOfAuditDropDownlist(projectError,stageOfAudit, error, keyValue){
        var warningMessage;
        if(!projectError){
            if (stageOfAudit) {
                if (error) {
                    warningMessage = '<span class="text-danger font-weight-bold"> Value <span class="text-dark">(' + stageOfAudit + ')</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>';
            }
        }else{
            warningMessage=`<span class="text-danger font-weight-bold">Please select project dropDown first</span>`;
        }
        return warningMessage;
    }
    
    checkForEmptyDistrict(districtKeyWord, districtMismatch){
        let validate=()=>{
            if(districtKeyWord){// if present
                return districtKeyWord;
            }else{
                return '--';
            }
        }
        if(districtMismatch){
            return `<td class="misMatchError">${districtKeyWord}<span class="text-center text-danger d-block font-weight-bold">Mismatch</span>`;
        }else{
            return `<td>${validate()}</td>`;
        }
        
    }
    
    checkForDuplicateSiteIdPoDetails(loopCount,jsonDataLength, curentJsonRow, nextJsonRow) {
        let checkMismatchedSiteDetails=(keyValue)=>{
            if(curentJsonRow[keyValue]!=nextJsonRow[keyValue]){
                // console.log(keyValue,true);
                curentJsonRow[keyValue+"Mismatch"]=true;
                nextJsonRow[keyValue+"Mismatch"]=true;
                errorValidationMapObj.set(keyValue+"Mismatch", "Error");
            }else{
                //  console.log(keyValue,false,"curentJsonRow.keyValue",curentJsonRow[keyValue],"nextJsonRow.keyValue",nextJsonRow[keyValue],"curentJsonRow",curentJsonRow);
            //   curentJsonRow[keyValue+"Mismatch"]=false;
            //   nextJsonRow[keyValue+"Mismatch"]=false;
               errorValidationMapObj.set(keyValue+"Mismatch", "noErrorFound");
            }
        }
        let checkDuplicateSiteDetails=()=>{
            if (curentJsonRow.siteId == nextJsonRow.siteId && 
                curentJsonRow.siteAssignedToEmpId==nextJsonRow.siteAssignedToEmpId &&
                curentJsonRow["siteVisitDate(yyyy-mm-dd)"]==nextJsonRow["siteVisitDate(yyyy-mm-dd)"]) {
                curentJsonRow.duplicate = true;
                nextJsonRow.duplicate = true;
                errorValidationMapObj.set("duplicateEntry", "Error");
            }else{
                errorValidationMapObj.set("duplicateEntry", "noErrorFound");
            }
        }
        let mismatchedSiteDetails=()=>{
            if(curentJsonRow.siteId == nextJsonRow.siteId){ // for same site with different site Details = mismatched
                checkMismatchedSiteDetails("siteName");
                checkMismatchedSiteDetails("latitude");
                checkMismatchedSiteDetails("longitude");
                checkMismatchedSiteDetails("customerName");
                checkMismatchedSiteDetails("circle");
                checkMismatchedSiteDetails("district");
            }
        }
        
        if ((loopCount + 1) < jsonDataLength) { // not to be out of bound
            if (curentJsonRow.siteId != null && nextJsonRow.siteId != null) { // not to be empty
            checkDuplicateSiteDetails();
            mismatchedSiteDetails();
            }
        }
    }
    
    checkRequiredCondition(loopCount, currentJsonRow){
        // console.log(currentJsonRow.siteAssignedToEmpId,currentJsonRow.project, currentJsonRow.stageOfAudit,currentJsonRow["siteVisitDate(yyyy-mm-dd)"]);
        let empId=currentJsonRow.siteAssignedToEmpId;
        let project=currentJsonRow.project;
        let stageOfAudit=currentJsonRow.stageOfAudit;
        let siteVisitDate=currentJsonRow["siteVisitDate(yyyy-mm-dd)"];  
        //-----------------explaination in last line in this file--------
        if(empId && project && stageOfAudit && siteVisitDate){  // if all values true then requirdCnt not need
            currentJsonRow.requiredCondition=false;
            }else{
                if(empId || project || stageOfAudit || siteVisitDate){
                    currentJsonRow.requiredCondition=true;      // if any one value true then requirdCnt need
                }else{
                    currentJsonRow.requiredCondition=false;
                }
            }
    }
    getDate(date){
        return date ? date.replaceAll('/','-'): undefined;
    }
    getEmpId(empId){
        return empId ? empId:undefined;
    }


    getOperationsTd(indexValue){
        let tdUI=`<td class="text-center opertionsTd"><i class="fa fa-clone pr-2 duplicateSiteDetailsRow" data-rowIndex="${indexValue}" data-toggle="tooltip" title="Duplicate Site Details" ></i> | <i class="fa fa-eraser pr-2 clearEmployeeAllocations" data-rowIndex="${indexValue}" data-toggle="tooltip" title="Clear Employee Allocation"></i> | <i class="fa fa-trash deleteCompleteRow" data-rowIndex="${indexValue}" data-toggle="tooltip" title="Delete Row"></i></td>`;
        return tdUI;
    }

}

//  rules
/*
1) In PO Details: -   If only PO number given allow to submit.
2) In PO Details: -   If no PO Details allow to submit.
3) In PO Details: - (empIdName, SitevisitDate, Project, stateOfAudit) If any one of these fields present all remaining fields need to insert.
    i.e (add only if all 4 fields values there)

*/
//------------------------------------------------------







