class ExistingSiteAllocations_DynamicTable{
    getTableUi(excelJson){
        let tableHeading =this.getTableHeading();
        let tableBody = this.getTableBody(excelJson);
        return tableHeading+tableBody;
    }
    getTableHeading(){
        let Thead=`<thead>
                        <tr>
                            <th>Sno</th>
                            <th>SiteId</th>
                            <th>PoNumber</th>
                            <th>EmpName(EmpId)</th>
                            <th>Site-Visit Date</th>
                            <th>Project</th>
                            <th>Stage Of Audit</th>
                            <th class="text-center operationTr">Operations</th>
                        </tr>
                </thead>`;
        return Thead;
    }
    getTableBody(excelJson){
        let Tbody='';
            EXISTING_SITE_ALLOCATIONS_SITE_ID_ARRAY=[]  // on every time making array empty
            EXISTING_SITE_ALLOCATIONS_SITEID_EMPID_DATE_ARRAY=[]    // on every time making array empty
            EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT={}// 
            
            
        let whileInitiallyLoopStart=(currentLoopIndex, currentLoopObj, nextLoopObj, lastLoopIndex)=>{
            let obj={
                siteId:currentLoopObj["siteId"],
                siteAssignedToEmpId:currentLoopObj["siteAssignedToEmpId"],
                siteVisitDate:currentLoopObj["siteVisitDate(yyyy-mm-dd)"]
            }
            let insertManagerDetailsInJson=()=>{
                currentLoopObj["managerId"]=loggedUserId,             // in index.php file
                currentLoopObj["managerName"]=loggedUserName          // in index.php file
            }
            insertManagerDetailsInJson();
            EXISTING_SITE_ALLOCATIONS_SITE_ID_ARRAY.push(currentLoopObj["siteId"]);
            EXISTING_SITE_ALLOCATIONS_SITEID_EMPID_DATE_ARRAY.push(JSON.stringify(obj)); 
            if(currentLoopIndex!=lastLoopIndex){
                this.checkForDuplicateEntries(currentLoopObj, nextLoopObj);
            }
        }
        for(let loopIndex=0; loopIndex<excelJson.length; loopIndex++){
            let backGroundColor = '';
            let duplicateKeyWord='';
            let currentLoopObj=excelJson[loopIndex];
            let nextLoopObj=excelJson[loopIndex+1];
            let uniqueId=currentLoopObj["siteId"]+"_"+currentLoopObj["siteAssignedToEmpId"]+"_"+currentLoopObj["siteVisitDate(yyyy-mm-dd)"];
            whileInitiallyLoopStart(loopIndex, currentLoopObj, nextLoopObj,  (excelJson.length-1));
            if(currentLoopObj.duplicate){
                backGroundColor = 'bg-light-danger ';
                duplicateKeyWord = '<br><span class="errorMsgTag text-danger   font-weight-bold">Duplicate</span>';
            }
            Tbody+=`<tr class="tableRow_${loopIndex} ${backGroundColor} tr_${uniqueId} trSiteId_${currentLoopObj["siteId"]}">
                        <td>${loopIndex+1}</td>
                        <td class="siteIdTd">${this.getSiteId_Td(currentLoopObj, currentLoopObj["siteId"], uniqueId)} ${duplicateKeyWord}</td>
                        <td class="poNumberTd">${this.getPONumber_Td(currentLoopObj, currentLoopObj["poNumber"], loopIndex)}</td>
                        <td class="empNameIdTd">${this.getEmpNameId_Td(currentLoopObj, loopIndex, uniqueId)}</td>
                        <td class="siteVisitDateTd">${this.getSiteVisitedDate_Td(currentLoopObj,currentLoopObj["siteVisitDate(yyyy-mm-dd)"], loopIndex, uniqueId)}</td>
                        <td class="projectTd">${this.getProject_Td(currentLoopObj, currentLoopObj["project"], loopIndex, uniqueId)}</td>
                        <td class="stageOfAuditTd">${this.getStageOfAudit_Td(currentLoopObj, currentLoopObj["stageOfAudit"], loopIndex, uniqueId)}</td>
                        <td class="text-center operationsTd"">${this.getOperations_Td(loopIndex)}</td>
                   </tr>`;
        }
        return `<tbody>${Tbody}</tbody>`;
        
    }
    getSiteId_Td(currentLoopObj, siteId, uniqueId){
        if(siteId){
            siteId=siteId.replaceAll("'","").replaceAll(' ','_');//trim the extra characters eg: '=>apostrophe
            currentLoopObj["siteId"]=siteId;
            return siteId;
        }else{
            this.updateErrorBucket(uniqueId, "SiteId Required");
            return `<span class="errorMsgTag d-block text-danger text-center  font-weight-bold">Required</span>`;
        }
    }
    getPONumber_Td(currentLoopObj, poNumber, index){
        let bgColor='';
        if(poNumber && poNumber!="Not Available"){
            poNumber=poNumber.replaceAll("'","");//trim the extra characters eg: '=>apostrophe
            currentLoopObj["poNumber"]=poNumber;
            
        }else{
            poNumber="Not Available";
            currentLoopObj["poNumber"]="Not Available";
            bgColor='bg-warning';
        }
        return `<input type="text" value="${poNumber}" class="form-control poDropDownInputList ${bgColor}" list="poDropDownList${index}" placeholder="Enter PO Number" data-rowIndex="${index}"/>
                        <datalist id="poDropDownList${index}">
                            <option>Not Available</option>
                        </datalist>`;
    }
    getEmpNameId_Td(currentLoopObj ,index, uniqueId){  
        let errorMsgTag='';
        let empId_matched_InEmpIdNameArray=false;
        let empId=currentLoopObj["siteAssignedToEmpId"];
        let selectOpenTag=`<select class="form-control empNameIdDropDown" data-rowIndex="${index}" data-errorKey="${uniqueId}">`;
        let selectEndTag=`</select>`;
        let optionTags=`<option value="" disabled selected>Select EmpId</option>`;
        let empIdNameArray=getLocalStorageValue("EMP_ID_NAME_ARRAY"); // fucntion call in main.js file
        
        empIdNameArray.forEach((loopObj)=>{
            if(loopObj.empId==empId){
                optionTags+=`<option value="${loopObj.empId}" selected>${loopObj.empId}(${loopObj.empName})</option>`;
                currentLoopObj["siteAssignedToEmpName"]=loopObj.empName;
                empId_matched_InEmpIdNameArray=true;
            }else{
                optionTags+=`<option value="${loopObj.empId}">${loopObj.empId}(${loopObj.empName})</option>`;
            }
        });
        if(empId){
            if(!empId_matched_InEmpIdNameArray){
                errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">EmpId not in list(<span class="text-dark">${empId}</span>)</span>`;
                this.updateErrorBucket(uniqueId, "EmpId Invalid");
            }
        }else{
            errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Please Select Engineer Id</span>`;
            this.updateErrorBucket(uniqueId, "EmpId Required");
        }
        return selectOpenTag + optionTags + selectEndTag + errorMsgTag;
    }
    
    getSiteVisitedDate_Td(currentLoopObj, siteVisitDate, index, uniqueId){
        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
        let errorMsgTag='';
        if(siteVisitDate){
            if(siteVisitDate.match(dateReg1) || siteVisitDate.match(dateReg2)){                   // validate date with YYYY/MM/DD formate
                 siteVisitDate=siteVisitDate.replaceAll('/','-');
                 currentLoopObj["siteVisitDate(yyyy-mm-dd)"]=siteVisitDate;
            }else{
                errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Invalid Formate(<span class="text-dark">${siteVisitDate}</span>)</span>`;
                this.updateErrorBucket(uniqueId, "SiteVisitDate Invalid");
            }
        }else{
            errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Required</span>`;
            this.updateErrorBucket(uniqueId, "SiteVisitDate Required");
        }
        return `<input type="date" value="${siteVisitDate}" class="form-control siteVisitDate" data-rowIndex="${index}" data-errorKey="${uniqueId}"/>${errorMsgTag}`;
    }
    getProject_Td(currentLoopObj, project, index, uniqueId){
        project=project ? project.toUpperCase():'';
        let errorMsgTag='';
        let project_matched_inProjectListArray=false;
        let selectOpenTag=`<select class="form-control projectDropDown" data-rowIndex="${index}" data-errorKey="${uniqueId}">`;
        let selectCloseTag=`</select>`;
        let optionTags='<option value="" disabled selected>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(project==value){
                    optionTags+=`<option value="${value}" selected>${value}</option>`;
                    project_matched_inProjectListArray=true;
                    currentLoopObj["project"]=project;                          //updating json to uppercase
                }else{
                    optionTags+=`<option value="${value}">${value}</option>`;
                }
            });
        if(project){
            if(!project_matched_inProjectListArray){
                errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Value (<span class="text-dark">${project}</span>) is not in dropdown list</span>`;
                this.updateErrorBucket(uniqueId, "Project Invalid");
            }
        }else{
        
            errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Please Select Project Name</span>`;
            this.updateErrorBucket(uniqueId, "Project Required");
                
        }
        return `${selectOpenTag}${optionTags}${selectCloseTag}${errorMsgTag}`;
    }
    
    getStageOfAudit_Td(currentLoopObj, stageOfAudit, index, uniqueId){
        stageOfAudit=stageOfAudit ? stageOfAudit.toUpperCase() :'';
        let selectedProjectName=currentLoopObj["project"];
        let errorMsgTag='';
        let stageOfAudit_matched_inStageOfAuditArray=false;
        let selectOpenTag=`<select class="form-control stageOfAuditDropdown" data-rowIndex="${index}" data-errorKey="${uniqueId}">`;
        let selectCloseTag=`</select>`;
        let optionTags=`<option value="" disabled selected>Select Stage Of Audit</option>`;
        let stageOfAuditListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[selectedProjectName];                //PROJECT_AND_STAGE_OF_AUDIT_DD in main.js
        if(stageOfAudit){
            if(stageOfAuditListArray){      //if project exist dropdown will have.
                stageOfAuditListArray.forEach(function(value){
                    if(stageOfAudit==value){
                        optionTags+=`<option value="${value}" selected>${value}</option>`;
                        stageOfAudit_matched_inStageOfAuditArray=true;
                        currentLoopObj["stageOfAudit"]=stageOfAudit;
                    }else{
                        optionTags+=`<option value="${value}">${value}</option>`;
                    }
                });
                if(!stageOfAudit_matched_inStageOfAuditArray){
                    errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Value (<span class="text-dark">${stageOfAudit}</span>) is not in dropdown list</span>`;
                    this.updateErrorBucket(uniqueId, "StageOfAudit Invalid");
                }
            }else{// if projet not there
                    errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Please select project dropdown first</span>`;
                    this.updateErrorBucket(uniqueId, "StageOfAudit Required");
            }
            
        }else{
            errorMsgTag=`<span class="font-weight-bold errorMsgTag d-block text-danger text-center ">Please Select Stage Of Audit</span>`;
            this.updateErrorBucket(uniqueId, "StageOfAudit Required");
        }
        return `${selectOpenTag}${optionTags}${selectCloseTag}${errorMsgTag}`;
    }
    getOperations_Td(indexValue){
        // let tdUI=`<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>`;
        let tdUI=`<i class="fa fa-clone pr-2 duplicateSiteDetailsRow" data-rowIndex="${indexValue}" data-toggle="tooltip" title="Duplicate Site Details" ></i> | <i class="fa fa-trash deleteCompleteRow" data-rowIndex="${indexValue}" data-toggle="tooltip" title="Delete Row"></i>`;
        return tdUI;
    }
    
    checkForDuplicateEntries(currentLoopObj, nextLoopObj){
        let crntSiteId=currentLoopObj["siteId"];
        let nxtSiteId=nextLoopObj["siteId"];
        let crntEmpId=currentLoopObj["siteAssignedToEmpId"];
        let nxtEmpId=nextLoopObj["siteAssignedToEmpId"];
        let crntDate=currentLoopObj["siteVisitDate(yyyy-mm-dd)"];
        let nxtDate=nextLoopObj["siteVisitDate(yyyy-mm-dd)"];
        if(crntSiteId == nxtSiteId && crntEmpId == nxtEmpId && crntDate == nxtDate) {
            currentLoopObj.duplicate=true;
            nextLoopObj.duplicate=true;
            
            let crnt_uniqueId=crntSiteId+"_"+crntEmpId+"_"+ crntDate; 
            let nxt_uniqueId=nxtSiteId+"_"+nxtEmpId+"_"+ nxtDate; 
            this.updateErrorBucket(crnt_uniqueId, "Duplicate Entry");
            this.updateErrorBucket(nxt_uniqueId, "Duplicate Entry");
        }
    }
    
    updateErrorBucket(uniqueId, errorType){
        let associateArrayIndexName=EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[uniqueId];
        let indexOfErrorValueNotExist=-1;
        
        if(!associateArrayIndexName){    //if array not exist                                  // in main.js 
            EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[uniqueId]=[];// creating array
        }
        
        let indexOfErrorValue=EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[uniqueId].indexOf(errorType);  // check if error already exist, if exist ignore
        if(indexOfErrorValue == indexOfErrorValueNotExist){
            EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[uniqueId].push(errorType);
        }
         
        
    }
}