define(["sb4core/DataUtil", "sb4core/loloader"], function (DataUtil, sb4Data) {
    function SB4GA(GATrackId) {
        this.GATrackId = GATrackId;
        if (!_.str.isBlank(this.GATrackId)) {
            var ga = document.createElement('script');
            ga.setAttribute("src", 'https://www.googletagmanager.com/gtag/js?id=' + GATrackId);
            ga.setAttribute("async", '');
            document.head.insertBefore(ga, document.head.firstChild);
            window.dataLayer = window.dataLayer || [];

            this.gtag('js', new Date());
            this.gtag('config', GATrackId);

            var self = this;
            SB4API.flowcontext.addListener(function (context) {
                self.reportPageViewEvent(context["name"]);
            })
        }

    };

    SB4GA.prototype.gtag = function () {
        if (!_.str.isBlank(this.GATrackId)) {
            window.dataLayer.push(arguments);
        }
    };

    SB4GA.prototype.reportEvent = function (name, params) {
        if ($.isPlainObject(params)) {
            this.gtag('event', DataUtil.parseString(name), params);
        } else {
            this.gtag('event', DataUtil.parseString(name));
        }
    };

    SB4GA.prototype.reportPageViewEvent = function (params) {
        var path = '/page-' + SB4API.currentScene['num'];
        if ($.isPlainObject(params)) {
            this.gtag('event', "page_view", params);
        } else {
            var title = '';
            if (params != undefined && params != null) {
                // title = params.toString();
                title = DataUtil.parseString(params)
            }
            this.gtag('event', "page_view", {
                "page_title": title,
                "page_path": path,
            });
        }

    };

    var gaData = _.find(sb4Data["lo"]["meta"]["entries"], function (o) {
        return o.id == 'analyticsid';
    });
    var gaId = "";
    if (gaData != null) {
        gaId = gaData.value;
    }
    SB4API.GA = new SB4GA(gaId);

});
