var scorm = pipwerks.SCORM;

function init() {
    scorm.init();
}

function set(param, value) {
    scorm.set(param, value);
}

function get(param) {
    scorm.get(param);
}

window.onload = function () {
    setTimeout(()=>{
        let vid = document.getElementById("videoElem");
        vid.addEventListener("ended", onEnded);
        let dur = scorm.get("cmi.suspend_data");
        vid.currentTime = dur;
        vid.play()
        console.log(" ********************************** ", vid.currentTime);
        
        let status = scorm.get("cmi.core.lesson_status");
        if (status !== "completed") {
            vid.currentTime = dur   ;
        }   
    }, 200)
    
    init();
};

function onEnded() {
    scorm.set("cmi.core.lesson_status","completed");
    scorm.save();
}

window.onunload = function () {
    let vid = document.getElementById("videoElem");
    scorm.set("cmi.suspend_data", vid.currentTime);
    scorm.save();
    scorm.quit();
};

var onCompleted = function (result) {
    // scorm.status('set', 'completed');
    // scorm.set("cmi.core.lesson_status","completed")
    if (!result.score) {
        return;
    }
    
    /* var masteryScore;
    if (scorm.version == '2004') {
        masteryScore = scorm.get('cmi.scaled_passing_score');
    } else if (scorm.version == '1.2') {
        masteryScore = scorm.get('cmi.student_data.mastery_score') / 100;
    }

    scorm.set('cmi.core.score.raw', result.score.scaled * 100);
    scorm.set('cmi.core.score.min', '0');
    scorm.set('cmi.core.score.max', '100');
    scorm.set('cmi.core.score.scaled', result.score.scaled * 100); */

    /* if (masteryScore === undefined) {
        // console.log(masteryScore);
        // scorm.status('set', 'completed');
        scorm.set("cmi.core.lesson_status","completed")
        scorm.save()
       
        
    } else {
        var passed = result.score.scaled >= masteryScore;
        if (scorm.version == '2004') {
            // scorm.status('set', 'completed');
            scorm.set("cmi.core.lesson_status","completed")
            scorm.save();
            if (passed) {
                scorm.set('cmi.success_status', 'passed');
            } else {
                scorm.set('cmi.success_status', 'failed');
            }
        } else if (scorm.version == '1.2') {
            if (passed) {
                scorm.status('set', 'passed');
            } else {
                scorm.status('set', 'failed');
            }
        }
    } */
};

H5P.externalDispatcher.on('xAPI', function (event) {
    if (event.data.statement.result) {
        // scorm.set("cmi.core.lesson_status","completed")
        onCompleted(event.data.statement.result);
        console.log(result);
    }
});
