const cheerio = require('cheerio');
const slugify=require('slugify');

function courselist(html) {
    $ = cheerio.load(html);
    tab2={};
    tab=[];
    studium="";
    pruefungsfach="";
    lvaname="";
    $('table').find('tr').each((index,element)=>{
        let element_first=$(element).find('td.nodeTable-title > div.ui-widget');
        if (element_first.hasClass("nodeTable-level-0")) {
            studium=element_first.text().replace(/^[\s\n]+|[\s\n]+$/g, '')
        }
        if (element_first.hasClass("nodeTable-level-1")) {
            pruefungsfach=element_first.text().replace(/^[\s\n]+|[\s\n]+$/g, '')
        }
        if (element_first.hasClass("nodeTable-level-2")) {
            modul=element_first.text().replace(/^[\s\n]+|[\s\n]+$/g, '')
        }
        if (element_first.hasClass("nodeTable-level-3")) {
            lvaname=element_first.text().replace(/^[\s\n]+|[\s\n]+$/g, '')
            tab2[lvaname]={"courses": []};
        }
        if (element_first.hasClass("nodeTable-level-4")) {
            let course_key=element_first.find("div.courseKey").text();
            course_key=course_key.replace(/^[\s\n]+|[\s\n]+$/g, '');
            let ects=$(($(element).find("td.nodeTable-short")).toArray()[2]).text()
            let std=$(($(element).find("td.nodeTable-short")).toArray()[1]).text()
            tab2[lvaname]["studium"] = studium
            tab2[lvaname]["modul"] = modul
            tab2[lvaname]["prufungsfach"] = pruefungsfach
            tab2[lvaname]["lvaname"] = lvaname
            tab2[lvaname]["ects"]=ects
            tab2[lvaname]["std"]=std
             tab2[lvaname]["courses"].push({
                 "href": element_first.find("a").attr("href"),
                 "lvanr": course_key.split(" ")[0],
                 "lvatyp": course_key.split(" ")[1],
                 "lvasem": course_key.split(" ")[2],
                 "courseKey": course_key,
                 "courseTitle":element_first.find("div.courseTitle").text().replace(/^[\s\n]+|[\s\n]+$/g, '')
             })
            tab.push({"href": element_first.find("a").attr("href"), 
                        "studium": studium, 
                        "pruefungsfach": pruefungsfach,
                        "modul":modul,
                        "ects":ects,
                        "std":std,
                        "courseKey": course_key,
                        "lvaname": lvaname,
                        "lvanr": course_key.split(" ")[0],
                        "lvatyp": course_key.split(" ")[1],
                        "lvasem": course_key.split(" ")[2],
                        "courseTitle":element_first.find("div.courseTitle").text().replace(/^[\s\n]+|[\s\n]+$/g, '')
                    })
        }
    })
    
    return {tab2};
}
module.exports = {courselist}