var xapiHandler = (function () {

    var _self = this;

    var _isInitialized = false;
    var _isEnabled = true;
    var allStatements = null;

    this.p_actor = 'Anonymous';
    this.p_actorId = 'Anonymous@example.com';

    var xAPI = {
        tracking: true,
        username: "Anonymous@example.com",
        endpoint: "",
        password: "Anonymous-12345",
        actor: {
            name: "client",
            mbox: "client.Employbridge@example.com",
            course: "Employbridge"
        }
    }

    var loginName = xAPI.username,
        endpoint = xAPI.endpoint,
        password = xAPI.password;

    var xapiWrapper = ADL.XAPIWrapper;

    this.config = {
        "endpoint": endpoint,
        "user": loginName,
        "password": password
    };


    let _params = null;

    let _qs_6_2 = ""


    let parseParams_1 = function (qs) {
     //   console.log("parseParams_1")
        let _params = null;
        let _win = window.parent || window
        try {
            // let _qs = (qs || window.location.search.substr(1)).split('+').join(' ');
            let _qs = (qs || _win.location.href).split('+').join(' ');

            if (_qs) {
                _params = {}
                let _keys = ["actor", "endpoint", "auth", "content_token", "externalRegistration", "activity_id", "registration", "externalConfiguration", "grouping", "content_endpoint"]
                var url = new URL(_qs);

                $.each(_keys, function (i, _key) {
                    var _val = url.searchParams.get(_key);
                    _params[_key] = _val;
                    // console.log(i, _key, _val)
                })
                _params.actor = JSON.parse(_params.actor);
          //      console.log("parseParams_1: ", _params)
            }
            if (_params.actor == null) {
                _params = null;
            }

        } catch (err) {
            console.error(err)
        }

        return _params;
    }


    let parseParams_2 = function (qs) {
        // let _qs = (window.location.search.substr(1)).split('+').join(' ');
        let _qs = (qs || window.location.href).split('+').join(' ');
        var _params = {},
            _tokens,
            _reg = /[?&]?([^=]+)=([^&]*)/g;

        while (_tokens = _reg.exec(_qs)) {
            _params[decodeURIComponent(_tokens[1]).trim()] = decodeURIComponent(_tokens[2]).trim();
        }

        return _params;

    }


    let getActorDetails = function (callback) {

     //   console.log("getActorDetails")
        _params = parseParams_1();

        if (_params) {

            let _actor = _params.actor
            let _name = (_actor.name).toString();
            let _accountName = _actor.account[0].accountName;
            let _tempArr = _accountName.split('|')
            let _userName = _tempArr[0];
            let _mbox = _tempArr[1];

            let _actor_details = {
                username: _mbox,
                endpoint: _params.endpoint + 'sandbox/',
                auth: _params.auth,
                actor: {
                    name: _name,
                    mbox: _mbox
                }
            }

            $.each(_actor_details, function (key, val) {
                xAPI[key] = val
            })

            if (callback) {
                callback()
            }
        } else {
            xAPI.tracking = false
        }
    }

    let updatexAPIDetails = function () {

      //  console.log("updatexAPIDetails")

        loginName = xAPI.username;
        endpoint = xAPI.endpoint;
        auth = xAPI.auth;

        _self.config = {
            "endpoint": endpoint,
            "user": loginName,
            "auth": xAPI.auth,
            "password": "",
        };

    }
    
    this.setActorDetail = function (actor) {
        if (_params == null) {
            let _fullName = actor.firstName + '.' + actor.lastName;
            xAPI.actor.name = _fullName + "_" + actor.aid + "_" + actor.wid;
            xAPI.actor.mbox = _fullName + "@example.com"
        }

        xAPI.actor.course = actor.course || "Employbridge_Employbridge";

        _self.p_actor = xAPI.actor.name;
        _self.p_actorId = xAPI.actor.mbox;
    }

    this.getActorDetail = function () {

        _self.p_actor = xAPI.actor.name;
        _self.p_actorId = xAPI.actor.mbox;

        return xAPI.actor;
        /*   "p_user": xAPI.actor.name + ":" + xAPI.actor.course,
            "mbox": xAPI.actor.mbox,
            "xAPI": xAPI
        }
        */
    }

    // this.setActorDetail(xAPI.actor)



    this.xapiIinitialize = function (callback) {

        getActorDetails(function () {
            updatexAPIDetails()
        //    console.log("xapiIinitialize")
            // _isEnabled = (lmsType.data == 'xAPI') ? true : false;
            _isEnabled = _xAPITracking = xAPI.tracking;
            if (!_isEnabled || !_xAPITracking) return;
            try {
                let _success = xapiWrapper.changeConfig(_self.config);
                _isInitialized = true;
            } catch (err) {
                console.error("xapiIinitialize: ", err.toString());
            }
            if (callback) {
                callback()
            }
        });

    }


    function prepareSetSimpleStatement(p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        try {

            let _strMailTo = _self.p_actorId,
                _strVerb = endpoint + "verbs/" + p_verb,
                _strObject = endpoint + "activities/" + p_object;

            return {
                "actor": {
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                },
                "verb": {
                    "id": _strVerb,
                    "display": {
                        "en-US": p_verb
                    }
                },
                "object": {
                    "id": _strObject,
                    "definition": {
                        "name": {
                            "en-US": p_object
                        },
                        "description": {
                            "en-US": p_object
                        }
                    }
                }
            };

        } catch (err) {
            console.error("ERROR - xapiHandler: prepareSetSimpleStatement:  ", err.toString());
        }
    }


    function prepareSetSimpleSuspendDataStatement(p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            let _strMailTo = _self.p_actorId,
                _strVerb = endpoint + "verbs/" + p_verb,
                _strObject = endpoint + "activities/" + p_verb;

            return {
                "actor": {
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                },
                "verb": {
                    "id": _strVerb,
                    "display": {
                        "en-US": p_verb
                    }
                },
                "object": {
                    "id": _strObject,
                    "definition": {
                        "name": {
                            "en-US": "course-progress-data"
                        },
                        "description": {
                            "en-US": p_object
                        }
                    }
                }
            };
        } catch (err) {
            console.error("ERROR - xapiHandler: prepareSetSimpleStatement:  ", err.toString());
        }
    }


    function prepareSetSimpleProgressDataStatement(p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        try {

            let _strMailTo = _self.p_actorId,
                _strVerb = endpoint + "verbs/" + p_verb,
                _strObject = endpoint + "activities/" + p_verb,
                _progress = parseInt(p_object.split("@")[0]) || 0,
                _completion = parseInt(p_object.split("@")[1]) || 0;

            return {
                "actor": {
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                },
                "verb": {
                    "id": _strVerb,
                    "display": {
                        "en-US": p_verb
                    }
                },
                "object": {
                    "id": _strObject,
                    "definition": {
                        "name": {
                            "en-US": "progress"
                        },
                        "description": {
                            "en-US": _progress + "%"
                        }
                    }
                },
                "result": {
                    "completion": (_completion == 1) ? true : false
                }
                /*
                 "success": (_completion == 1) ? true : false,
                    "extensions": {
                        "end-point": _progress
                    }
                */
            };
        } catch (err) {
            console.error("ERROR - xapiHandler: prepareSetSimpleStatement:  ", err.toString());
        }
    }

    function prepareSetSimpleLoginDataStatement(p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            let _strMailTo = _self.p_actorId,
                _strVerb = endpoint + "verbs/" + p_verb,
                _strObject = endpoint + "activities/" + p_verb;

            return {
                "actor": {
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                },
                "verb": {
                    "id": _strVerb,
                    "display": {
                        "en-US": p_verb
                    }
                },
                "object": {
                    "id": _strObject,
                    "definition": {
                        "name": {
                            "en-US": "course-login-data"
                        },
                        "description": {
                            "en-US": p_object
                        }
                    }
                }
            };
        } catch (err) {
            console.error("ERROR - xapiHandler: prepareSetSimpleStatement:  ", err.toString());
        }
    }


    function prepareGetSimpleStatement(p_actor, p_verb, p_object, _searchParams) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            if (p_actor) {
                let _strMailTo = _self.p_actorId;
                _searchParams['agent'] = JSON.stringify({
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                });
            }
            if (p_verb) {
                let _strVerb = endpoint + "verbs/" + p_verb;
                _searchParams['verb'] = _strVerb
            }
            if (p_object) {
                let _strObject = endpoint + "activities/" + p_object;
                _searchParams['activity'] = _strObject
            }
            //       console.log("prepareGetSimpleStatement: ", _searchParams)
        } catch (err) {
            console.error("ERROR - xapiHandler: prepareGetSimpleStatement:  ", err.toString());
        }
    }


    function prepareGetSimpleSuspendDataStatement(p_actor, p_verb, p_object, _searchParams) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            if (p_actor) {
                let _strMailTo = _self.p_actorId;
                _searchParams['agent'] = JSON.stringify({
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                });
            }
            if (p_verb) {
                let _strVerb = endpoint + "verbs/" + p_verb;
                _searchParams['verb'] = _strVerb
            }
            if (p_object) {
                let _strObject = endpoint + "activities/" + p_object;
                _searchParams['statements'] = _strObject
            }
            //       console.log("prepareGetSimpleSuspendDataStatement: ", _searchParams)
        } catch (err) {
            console.error("ERROR - xapiHandler: prepareGetSimpleSuspendDataStatement:  ", err.toString());
        }
    }

    function prepareGetSimpleLoginDataStatement(p_actor, p_verb, p_object, _searchParams) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            if (p_actor) {
                let _strMailTo = _self.p_actorId;
                _searchParams['agent'] = JSON.stringify({
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                });
            }
            if (p_verb) {
                let _strVerb = endpoint + "verbs/" + p_verb;
                _searchParams['verb'] = _strVerb
            }
            if (p_object) {
                let _strObject = endpoint + "activities/" + p_object;
                _searchParams['statements'] = _strObject
            }
            //       console.log("prepareGetSimpleLoginDataStatement: ", _searchParams)
        } catch (err) {
            console.error("ERROR - xapiHandler: prepareGetSimpleLoginDataStatement:  ", err.toString());
        }
    }

    this.xapiGetAllData = function (p_actor, p_verb, p_object) {
        if (!_isEnabled || !_xAPITracking) return;
        try {
            let _searchParams = xapiWrapper.searchParams();
            prepareGetSimpleStatement(p_actor, '', '', _searchParams);
            _searchParams['related_activities'] = true;
            _searchParams['related_agents'] = true;
            let _stmts = xapiWrapper.getStatements(_searchParams);

            //      console.log("xapiGetAllData: ", _stmts.statements)
            return _stmts.statements;
        } catch (err) {
            console.error("ERROR - xapiHandler: xapiGetData:  ", err.toString());
        }
    }

    this.xapiGetData = function (p_actor, p_verb, p_object) {
        if (!_isEnabled || !_xAPITracking) return;

        /* if (!checkONLineOffline()) {
             return null;
         }
         */

        try {
            let _searchParams = xapiWrapper.searchParams();
            prepareGetSimpleStatement(p_actor, p_verb, p_object, _searchParams);
            _searchParams['related_activities'] = true;
            _searchParams['related_agents'] = true;
            let _stmts = xapiWrapper.getStatements(_searchParams);
            //      console.log("xapiGetData: ", _stmts.statements)
            return _stmts.statements;
        } catch (err) {
            console.error("ERROR - xapiHandler: xapiGetData:  ", err.toString());
        }
    }

    this.xapiGetSuspendData = function () {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            let _searchParams = xapiWrapper.searchParams(),
                _result = '',
                p_actor = _self.p_actor,
                p_verb = "course-data",
                p_object = "course-data";

            prepareGetSimpleSuspendDataStatement(p_actor, p_verb, p_object, _searchParams);

            _searchParams['related_activities'] = true;
            _searchParams['related_agents'] = true;

            let _stmts = xapiWrapper.getStatements(_searchParams);

            //   console.log("xapiGetSuspendData: ", _stmts)

            if (_stmts.statements.length > 0) {
                // return _stmts.statements[0].object.definition.description["en-US"].replace("@", "||");
                _result = _stmts.statements[0].object.definition.description["en-US"];
            }

            //  console.log("xapiGetSuspendData: ", _result)
            return _result

        } catch (err) {
            console.error("ERROR - xapiHandler: xapiGetSuspendDataData:  ", err.toString());
        }
    }

    this.xapiGetLoginData = function () {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            var _searchParams = xapiWrapper.searchParams(),
                _result = '',
                p_actor = _self.p_actor,
                p_verb = "login-data",
                p_object = "?verb=" + endpoint + "verbs/" + p_verb;

            prepareGetSimpleLoginDataStatement(p_actor, p_verb, p_object, _searchParams);

            _searchParams['related_activities'] = true;
            _searchParams['related_agents'] = true;

            let _stmts = xapiWrapper.getStatements(_searchParams);
            if (_stmts.statements.length > 0) {
                // return _stmts.statements[0].object.definition.description["en-US"].replace("@", "||");
                _result = _stmts.statements[0].object.definition.description["en-US"];
            }

            //  console.log("xapiGetLoginData: ", _result)
            return _result;

        } catch (err) {
            console.error("ERROR - xapiHandler: xapiGetSuspendDataData:  ", err.toString());
        }
    }

    var checkONLineOffline = function () {
        try {
            var status = navigator.onLine ? true : false,
                _msg = (status == true) ? "'You are online!" : 'You are offline!'
            //  console.log('checkONLineOffline:    ', _msg)

        } catch (err) {
            console.error("xapiManager:	", err.toString())
        }
        return status
    }

    this.xapiSetData = function (p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        /*  if (!checkONLineOffline()) {
              return null;
          }
          */

        try {
            let p_actor = _self.p_actor,
                _stmts = prepareSetSimpleStatement(p_actor, p_verb, p_object),
                _resp_obj = xapiWrapper.sendStatement(_stmts);
            //   console.log("xapiSetData:    ", _resp_obj)
            return _resp_obj
        } catch (err) {
            console.error("ERROR: Please check your Network Connection")
            console.error("ERROR:  - xapiSetData:  ", err.toString());

        }
    }

    this.xapiSetSuspendData = function (p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            let p_actor = _self.p_actor,
                _stmts = prepareSetSimpleSuspendDataStatement(p_actor, p_verb, p_object),
                _resp_obj = xapiWrapper.sendStatement(_stmts);
            //     console.log("xapiSetSuspendData: ", _resp_obj)
            return _resp_obj
        } catch (err) {
            console.error("ERROR: xapiHandler - xapiSetSuspendData:  ", err.toString());
        }

    }

    this.xapiSetLoginData = function (p_actor, p_verb, p_object) {
        if (!_isEnabled || !_xAPITracking) return;
        try {
            let p_actor = _self.p_actor,
                _stmts = prepareSetSimpleLoginDataStatement(p_actor, p_verb, p_object),
                _resp_obj = xapiWrapper.sendStatement(_stmts);
            //      console.log("xapiSetLoginData: ", _resp_obj)
            return _resp_obj
        } catch (err) {
            console.error("ERROR: xapiHandler - xapiSetLoginData:  ", err.toString());
        }
    }

    this.xapiSetProgressData = function (p_actor, p_verb, p_object) {
        if (!_isEnabled || !_xAPITracking) return;
        try {
            let p_actor = _self.p_actor,
                _stmts = prepareSetSimpleProgressDataStatement(p_actor, p_verb, p_object),
                _resp_obj = xapiWrapper.sendStatement(_stmts);
            //       console.log("xapiSetProgressData: ", _resp_obj)
            return _resp_obj;
        } catch (err) {
            console.error("ERROR: xapiHandler - xapiSetProgressData:  ", err.toString());
        }
    }


    this.xapiSetQuestionData = function (qData) {
        if (!_isEnabled || !_xAPITracking) return;
        try {
            let _stmts = prepareSetQuestionStatement(qData),
                _resp_obj = xapiWrapper.sendStatement(_stmts);
            return _resp_obj;
        } catch (err) {
            console.error("ERROR: xapiHandler - xapiSetQuestionData:  ", err.toString());
        }
    }

    function prepareSetQuestionStatement(qData) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            let _p_verb = "answered",
                _strMailTo = _self.p_actorId,
                _strVerb = endpoint + "verbs/" + _p_verb,
                _strObject = endpoint + "activities/assessment/question-" + qData.sNo;

            return {

                "actor": {
                    "objectType": "Agent",
                    "mbox": "mailto:" + _strMailTo,
                    "name": _self.p_actor
                },

                "verb": {
                    "id": _strVerb,
                    "display": {
                        "en-US": _p_verb
                    }
                },

                "object": {
                    "id": _strObject,
                    "definition": {
                        "extensions": {
                            "http://example.com/assessment": {
                                "Question:": qData.sNo + ". " + qData.qTxt,
                                "Options": qData.options,
                                "Correct-Option's": qData.cAnswer,
                                "User-Option's": qData.uAnswer,
                                "Selected-Button": qData.uClickedBtn,
                                "Result": qData.result,
                                "Question-Related-To-Lesson": qData.qlesson,
                                "User-To-Offer": qData.uCourseToOffer,
                            }
                        }
                    }
                }

            };

        } catch (err) {
            console.error("ERROR - xapiHandler: prepareSetQuestionStatement:  ", err.toString());
        }
    }


    this.getAllAssetStatus = function (_assetsArr) {

        if (!_isEnabled || !_xAPITracking) return;

        if (!_assetsArr && allStatements) return;

        var _statusArr = [];
        var _stmtsLen = allStatements.length

        for (var i = 0; i < _stmtsLen; i++) {

            var _activityID = allStatements[i].object.definition.name['en-US'];
            var _pNo = _assetsArr.indexOf(_activityID);

            if ((_pNo != -1)) {

                var _assetStatus = allStatements[i].verb.display['en-US']
                var _sALen = _statusArr.length;
                var _isTrue = true;
                for (var j = 0; j < _sALen; j++) {
                    if ((_statusArr[j].id == _activityID)) {
                        if ((_statusArr[j].status == _assetStatus) || (_statusArr[j].status == 'completed')) {
                            _isTrue = false;
                            break;
                        }
                    }
                }

                if (_isTrue) {
                    var _obj = {};
                    _obj.id = _activityID
                    _obj.pNo = _pNo;
                    _obj.status = allStatements[i].verb.display['en-US'];
                    _statusArr.push(_obj)
                }
            }
        }

     //   console.log("getAllAssetStatus: ", _statusArr)
        return _statusArr;
    }

    this.xapiSetCompletion = function (p_actor, p_verb, p_object) {

        if (!_isEnabled || !_xAPITracking) return;

        try {
            let p_actor = _self.p_actor,
                _stmts = prepareSetSimpleStatement(p_actor, p_verb, p_object);
            _stmts['result'] = {
                "completion": true
            }
            let _resp_obj = xapiWrapper.sendStatement(_stmts);
            return _resp_obj
        } catch (err) {
            console.error("ERROR: xapiHandler - xapiSetData:  ", err.toString());
        }
    }

    return {
        initialize: xapiIinitialize,
        setCompletion: xapiSetCompletion,
        getAllData: xapiGetAllData,
        getData: xapiGetData,
        setData: xapiSetData,
        setActorDetail: setActorDetail,
        getActorDetail: getActorDetail,
        getSuspendData: xapiGetSuspendData,
        setSuspendData: xapiSetSuspendData,
        getLoginData: xapiGetLoginData,
        setLoginData: xapiSetLoginData,
        setProgressData: xapiSetProgressData,
        setQuestionData: xapiSetQuestionData
    };

})();