<div id="attendenceTable" class="attendenceTable">
    <div class="tableHeader">
        <h3>Attendance List</h3>
        <div id="filterDiv" class="filterDiv"></div>
    </div>
    <div class='table'></div>
    <div class='mobileViewTable'>
        <div class="tableHeader">
            <h3>Attendance List</h3>
            <div id= "mobileFilterDiv"class="filterDiv">
                <div id= "mobileFilterDiv1"class="dropDownDiv">               
                </div> 
            </div>
        </div>
        <div class="userDetails"></div>        
    </div>
</div>
<script type="text/javascript">
const tableData = {{{tableData}}};
const tableHeader = ['Name of Live Class', 'Couse Name', 'Attended Time', 'Date Conducted', 'Status'];
const tableKeys = ['className','courseName','attendedTime','dateConducted','status'];

//document.querySelector('.userDetails').appendChild(createUserDetails(tableData, tableKeys));

function createUserDetails(json, keys) {
    var userDiv = document.createElement('div');
    userDiv.setAttribute('id', 'userDetailId')
    json.forEach(function(object){        
        var userDetail = document.createElement('div');
                userDetail.innerHTML = `<div class="userDetailDiv">
                <div class="userDetailRow">
                    <span class="detailHeading">Name of Live class</span>
                    <span class="detailSubHeading classname">${object['className']}</span>
                </div>
                <div class="userDetailRow">
                    <span class="detailHeading">Course Name</span>
                    <span class="detailSubHeading">${object['courseName']}</span>
                </div>
                <div class="userDetailRow userDetailCol">
                    <div>
                        <span class="detailHeading">Attended Time <a class="attendencePopover" href="javascript:void(0);" data-toggle="popover" data-placement="top" data-content="Number of minutes you have attended the class"><i class="fa fa-info-circle" aria-hidden="true"></i></a></span>
                        <span class="detailSubHeading">${object['attendedTime']} min</span>
                    </div>
                    <div>
                        <span class="detailHeading">Date Conducted</span>
                        <span class="detailSubHeading">${object['dateConducted']}</span>
                    </div>
                </div>
                <div class="userDetailRow userDetailCol">
                    <div class="statusDiv">
                        <span class="detailHeading">Status</span>                        
                        ${ object['status'] === "Present"?  `<span class="userStatus present"><span class="presentDot dot"></span>${object['status']}</span>` : `<span class="userStatus absent"><span class="absentDot dot"></span>${object['status']}</span>`}
                    </div>                    
                </div>
            </div>`;
            userDiv.appendChild(userDetail);   
    });
    return userDiv;
}


function createAttendenceTable(tableData) {
  var table = document.createElement('table');
  table.setAttribute('id', 'userAttendenceTable')
  var keys = tableHeader;
  table.appendChild(makeTHEAD(keys));
  table.appendChild(makeTBODY(tableData, tableKeys));
  return table;
}

function makeTHEAD(keys) {
  var thead = document.createElement('thead');
  var tr = document.createElement('tr');
  keys.forEach(function(key){
    var th = document.createElement('th');
        if(key == 'Attended Time'){
            th.innerHTML = `${key} <a class="attendencePopover" href="javascript:void(0);" data-toggle="popover" data-content="Number of minutes you have attended the class"><i class="fa fa-info-circle" aria-hidden="true"></i></a>`;
        } else {
            th.innerHTML = key;
        }                
        tr.appendChild(th)
    });
    thead.appendChild(tr);
    return thead;
}

function makeTBODY(json, keys) {
      var tbody = document.createElement('tbody');      
  json.forEach(function(object){
    console.log('object==', object);
      let tr = document.createElement('tr');
    keys.forEach(function(key){
      console.log('key==', key);  
      var td = document.createElement('td');
      if(object[key] == 'Present'){
        td.innerHTML = `<div class="userStatus present"><span class="presentDot dot"></span>${object[key]}</div>`
      }else if(object[key] == 'Absent'){
        td.innerHTML = `<div class="userStatus absent"><span class="absentDot dot"></span>${object[key]}</div>`
      } else if(key === 'attendedTime') {
        td.innerHTML = `<div class=""><span class=""></span>${object[key]} min</div>`
      } else {
        td.textContent = object[key];
      }
      tr.appendChild(td);
    });
      tbody.appendChild(tr);
  });
    return tbody;
}

$(document).ready(function(){
    $('.attendencePopover').hover(function() {
        $('[data-toggle="popover"]').popover(); 
    })      
});

function tableFromArray(tableData) {
  var array_of_keys = [];
  tableData.forEach(function(obj){
    Object.keys(obj).forEach(function(key){
      if (!(array_of_keys.includes(key))) {
        array_of_keys.push(key);
      }
    });
  });
  return array_of_keys.sort();
}



    $(document).ready(function () { 
        var isMobile = parseFloat(window.innerWidth)/parseFloat(window.innerHeight);
        if(isMobile < 1) {
            renderTableWithComponents({
                mode:'mobileView',
                statusDropDownParent:'mobileFilterDiv1',
                courseDropDownParent:'mobileFilterDiv',
                classTypeDropdownParent:'mobileFilterDiv1',
                paginationParent:'attendenceTable',
                tableParentClassName:'.userDetails',
                tableId:'userDetailId',
                initailTableData:tableData,
                statusDropDownCustomClass:'select1',
                courseDropDownCustomClass:'select3',
                classTypeDropdonCustomClass:'select2',
                ulWidth1:'141px',
                ulWidth3:'141px',
                ulWidth2:'100%',
            });
        } else {
            renderTableWithComponents({
                mode:'desktopView',
                statusDropDownParent:'filterDiv',
                courseDropDownParent:'filterDiv',
                classTypeDropdownParent:'filterDiv',
                paginationParent:'attendenceTable',
                tableParentClassName:'.table',
                tableId:'userAttendenceTable',
                initailTableData:tableData,
                statusDropDownCustomClass:'select1',
                courseDropDownCustomClass:'select2',
                classTypeDropdonCustomClass:'select3',
                ulWidth1:'160px',
                ulWidth2:'313px',
                ulWidth3:'249px',
            });
        }            
    });

    // rendering table,dropdown and pagination with filters
    function renderTableWithComponents(parameters){
            // code for dropdown filter
            let statusDropDown = new CreateDropDown(
                {
                    parentId:parameters.statusDropDownParent,
                    childNames:[
                        'All',
                        ...getValuesFromData({
                            "key":"status",
                            "data":parameters.initailTableData,
                        })
                    ],
                    name:'Status',
                    customClass:parameters.statusDropDownCustomClass,
                    ulWidth:parameters.ulWidth1
                }
            );

            let courseNameDropDown = new CreateDropDown(
                {
                    parentId:parameters.courseDropDownParent,
                    childNames:[
                        'All',
                        ...getValuesFromData({
                            "key":"courseName",
                            "data":parameters.initailTableData
                        })
                    ],
                    name:'Course',
                    customClass:parameters.courseDropDownCustomClass,
                    ulWidth:parameters.ulWidth2
                }
            );
            
            let classTypeDropDown = new CreateDropDown(
                {
                    parentId:parameters.classTypeDropdownParent,
                    childNames:[
                        'All',
                        ...getValuesFromData({
                            "key":"classType",
                            "data":parameters.initailTableData
                        })
                    ],
                    name:'Class type',
                    customClass:parameters.classTypeDropdonCustomClass,
                    ulWidth:parameters.ulWidth3
                }
            );            
            
            window.onclick = function(e){
                statusDropDown.hideDropDown(e);
                courseNameDropDown.hideDropDown(e);
                classTypeDropDown.hideDropDown(e);
            }

            let activeStatusDropDownValue = statusDropDown.getInitailValue();
            let activeCourseNameDropDown = courseNameDropDown.getInitailValue();
            let activeClassTypeDropDown = classTypeDropDown.getInitailValue();
            let filteredData = getFilterTableData({
                "status":activeStatusDropDownValue,
                "courseName":activeCourseNameDropDown,
                "classType":activeClassTypeDropDown,
                "data":parameters.initailTableData
            }
            );
            let pagination = new Pagination({
                parentId:parameters.paginationParent,
                data:filteredData,
                itemsPerPage:10,
                totalOnScreenPaginationButtons:3,
            });
            renderTableWithTableData();
            // get data when pagination changes
            pagination.element.addEventListener('change',(e)=>{
                renderTableWithTableData();
            });
        statusDropDown.dropDown.addEventListener('change',(e)=>{
            activeStatusDropDownValue = e.detail.activeValue();
            filteredData = getFilterTableData({
                "status":activeStatusDropDownValue,
                "courseName":activeCourseNameDropDown,
                "classType":activeClassTypeDropDown,
                "data":parameters.initailTableData
            }
            );
            pagination.remove();
            pagination = new Pagination({
                parentId:parameters.paginationParent,
                data:filteredData,
                itemsPerPage:10,
                totalOnScreenPaginationButtons:3,
            });
            renderTableWithTableData();
            pagination.element.addEventListener('change',(e)=>{
                renderTableWithTableData();
            })
        });
        courseNameDropDown.dropDown.addEventListener('change',(e)=>{
            activeCourseNameDropDown = e.detail.activeValue();
            filteredData = getFilterTableData({
                "status":activeStatusDropDownValue,
                "courseName":activeCourseNameDropDown,
                "classType":activeClassTypeDropDown,
                "data":parameters.initailTableData
            }
            );
            pagination.remove();
            pagination = new Pagination({
                parentId:parameters.paginationParent,
                data:filteredData,
                itemsPerPage:10,
                totalOnScreenPaginationButtons:3,
            });
            renderTableWithTableData();
            pagination.element.addEventListener('change',(e)=>{
                renderTableWithTableData();
            })
        });
        classTypeDropDown.dropDown.addEventListener('change',(e)=>{
            activeClassTypeDropDown = e.detail.activeValue();
            filteredData = getFilterTableData({
                "status":activeStatusDropDownValue,
                "courseName":activeCourseNameDropDown,
                "classType":activeClassTypeDropDown,
                "data":parameters.initailTableData
            }
            );
            pagination.remove();
            pagination = new Pagination({
                parentId:parameters.paginationParent,
                data:filteredData,
                itemsPerPage:10,
                totalOnScreenPaginationButtons:3,
            });
            renderTableWithTableData();
            pagination.element.addEventListener('change',(e)=>{
                renderTableWithTableData();
            })
        });
        function renderTableWithTableData(){
            if(parameters.mode=='mobileView'){
                document.getElementById(parameters.tableId)?.remove();
                document.querySelector(parameters.tableParentClassName).appendChild(createUserDetails(pagination.getInitialData(), tableKeys));
            }
            else if(parameters.mode=='desktopView'){
                document.getElementById(parameters.tableId)?.remove();
                document.querySelector(parameters.tableParentClassName).appendChild(createAttendenceTable(pagination.getInitialData()));
            }
        }
    }

    // Table filter code
    function getFilterTableData(data){
        const status = data["status"];
        const courseName = data["courseName"];
        const classType = data["classType"];
        const rawTableData = data.data;
        const tempFilteredData = rawTableData.filter((value)=>{
            const filter1 = status=='All'?true:value["status"] == status;
            const filter2 = courseName=='All'?true:value["courseName"] == courseName;
            const filter3 = classType=='All'?true:value["classType"] == classType;
            return filter1 && filter2 && filter3
        });
        return tempFilteredData        
    }

    //creating dynamic drop down
    class CreateDropDown{
        constructor(data){
            let thisClass = this;
            this.id ='Dropdown'+ Math.floor((Math.random() * 100000000) + 1);;
            this.dropDownOpenState = false;
            this.dropDownSelectIndex = 0;
            this.parent= document.getElementById(data.parentId);
            this.childNames = data.childNames;
            this.dropDown = document.createElement('DIV');
            this.dropDown.classList.add('dropdown');
            this.parent.appendChild(this.dropDown);
            this.button = document.createElement('button');
            this.button.classList.add('btn-outline-secondary');
            this.button.classList.add('dropdown-toggle');
            this.button.setAttribute('role','button');
            this.button.setAttribute('dataToggle','dropdown');
            this.button.setAttribute('ariaExpanded',"false");
            this.button.innerHTML = '<span class="buttonHeading">Status: </span>'
            this.dropDown.appendChild(this.button);
            this.ul = document.createElement('ul');
            this.ul.classList.add('dropdown-menu');
            if(data.customClass){
                this.button.classList.add(data.customClass);
                this.ul.style.width = data.ulWidth;
                this.ul.style.minWidth = data.ulWidth;
                }
            this.ul.setAttribute('ariaLabelledby','dropdownMenuLink');
            this.ul.setAttribute('id',this.id+'.optionholder');
            this.changeEvent = new CustomEvent('change', {
                bubbles: true,
                detail: { activeValue: () => {
                    return thisClass.childNames[thisClass.dropDownSelectIndex]
                } }
            });
            this.getInitailValue = ()=>{
                return thisClass.childNames[thisClass.dropDownSelectIndex]
            }
            this.dropDown.appendChild(this.ul);
            this.childOptions = [];
            for(let i=0;i<this.childNames.length;i++){
                this.childOptions[i] = document.createElement('li');
                this.ul.appendChild(this.childOptions[i]);
                this.childOptions[i].classList.add('dropdown-item');
                this.childOptions[i].classList.add('dropdown-option--hoverColor')
                this.childOptions[i].innerText = this.childNames[i];
                this.childOptions[i].setAttribute('id',this.id+'.'+i);
                this.childOptions[i].onclick = function(e){
                    thisClass.dropDownSelectIndex=parseInt(this.id.replace(thisClass.id+'.',''));
                    thisClass.changeInnerTextOfParent();
                    thisClass.dropDown.dispatchEvent(thisClass.changeEvent);
                };
            }
            this.dropDown.onclick = function(e){
                //e.stopPropagation();
                if(thisClass.dropDownOpenState){
                    thisClass.ul.style.display  = 'none';
                    thisClass.dropDownOpenState = false;

                }
                else{
                    thisClass.ul.style.display  = 'block';
                    thisClass.dropDownOpenState = true;
                }
            }
            this.changeInnerTextOfParent = function(){
                thisClass.button.innerHTML = '<span class="buttonHeading">'+data.name+': </span> <span class="buttonSubHeading">'+thisClass.childNames[thisClass.dropDownSelectIndex]+'</span> ';

            }
            this.hideDropDown = function(e){
                const isSelfClicked = ((e.target == thisClass.button)|| (e.target.parentNode == thisClass.button))
                if(thisClass.dropDownOpenState && !isSelfClicked){
                    thisClass.ul.style.display  = 'none';
                    thisClass.dropDownOpenState = false;

                }
            }
            
            thisClass.changeInnerTextOfParent();
        }
    }

    function getValuesFromData(data){
        const key = data.key;
        const rawTableData = data.data;
        let tempValues = [];
        rawTableData.forEach((value)=>{
            tempValues.push(value[key]);
        });
        tempValues = [... new Set(tempValues)]
        return tempValues
    }
</script>