var logBehaviorUser = (function(){
    //obj defaults untuk menentukan yang akan diambil
    var defaults = {
        clickDetails: true,
        context: true,
        //Menentukan AksiA
        actionItem: {
            processOnAction: false,
            event: '',
            token:''
        },
        processTime: 0,
        processData: function(results){
        },
    },

    //Behavior yang akan diambil1
    results = {
        nameweb : '',
        user_info: {
            ip_address_public:'',
            ip_address_client:'',
            mac_address:'',
        }, 
        location:{
            country: '',
            province:'',
            city:'',   
        },
        browser: {
            browserName: '',
            browserVer:'',
        },
        page : {
            name_page :'',
            date_access:'',
            time_access:'',
            time_accessname:'',
            total_time:0, //in second  
        },
        behavioruser: { 
            button:[],
            image: [],
            video:[],
            other:[],
        },
    },

    support = !!document.querySelector && !!document.addEventListener, settings;
    
    //Fungsi helper untuk pengambilan data
    var helperActions = {
       
        getPage:function(){
            results.page.name_page = window.location.pathname;
        },

        getMacAddress:function(){
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: "http://useranalyticgiw.giw/api/loadmacaddress",
                success: function(result) {
                    results.user_info.mac_address=result.data;
                    // console.log(result);
                },error: function(xhr){
                    alert(xhr.status+'-'+xhr.statusText);
                }
            })
        },
        
        getTokenkey:function(){
            $token = settings.actionItem.token;
    
            // alert("aa"+$token);
    
            $.ajax({
                type: 'POST',
                dataType: 'json',
                data    : {'myData':$token},
                url: "http://useranalyticgiw.giw/api/loadtoken",
    
                success: function(result) {
                    results.nameweb=result.data;
                    // alert(result.data);
                },error: function(xhr){
                    alert(xhr.status+'-'+xhr.statusText);
                }
            })
        },
    
        getIPAddress:function(){
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: "http://useranalyticgiw.giw/api/loadipaddress",
                success: function(result) {
                    results.user_info.ip_address_public=result.data;
                    // console.log(result);
                },error: function(xhr){
                    alert(xhr.status+'-'+xhr.statusText);
                }
            })
        },
        
        //Mendapatkan Browser client
        browser: function(){  
            var userAgent   = navigator.userAgent;
            var opera       = (userAgent.indexOf('Opera') != -1);
            var chrome      = (userAgent.indexOf('Chrome') != -1);
            var ie          = (userAgent.indexOf('MSIE') != -1);
            var gecko       = (userAgent.indexOf('Gecko') != -1);
            var netscape    = (userAgent.indexOf('Mozilla') != -1);
            var safari      = (userAgent.indexOf('Safari') != -1);        
    
            var version     = navigator.appVersion;
                       
            if (opera){
                results.browser.browserName= "opera";
                results.browser.browserVer = version;
            }
            else if (chrome){
                results.browser.browserName= "chrome";
                results.browser.browserVer = version;

            }
            else if (gecko){
                results.browser.browserName= "Mozila";
                results.browser.browserVer = version;

            }              
            else if (ie){
                results.browser.browserName= "Internet Explorer";
                results.browser.browserVer = version;
            }       
            else if (netscape){
                results.browser.browserName= "netscape";
                results.browser.browserVer = version;
            }
            else if (safari){
                results.browser.browserName= "Safari";
                results.browser.browserVer = version;
            }else{
                results.browser.browserName= navigator.userAgent;
                results.browser.browserVer = version;

            }
        },

        //Mendapatkan info user
        getLocationUser: function(){
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: "http://www.geoplugin.net/json.gp",
                success: function(data) {
                    $ip         = data.geoplugin_request;
                    $country    = data.geoplugin_countryName;
                    $province   = data.geoplugin_region;
                    $city       = data.geoplugin_city;

                    results.user_info.ip_address_client =$ip;
                    results.location.country =$country;
                    results.location.province =$province;
                    results.location.city =$city;     
                }
            })
        },
 
    }

    function getSettings(defaults, options){
        var option;
        for(option in options){
            if(options.hasOwnProperty(option)){
                defaults[option] = options[option];
            }
        }
        return defaults;
    }

     // inisilaisasi untuk event listener
    function init(options){
        if (options && typeof options === "object") {
            settings = getSettings(defaults, options);
        }
        
        $.ajax({    
            type    : "POST",
            url     : 'http://useranalyticgiw.giw/api/keyval',
            data    : {'myData':settings.actionItem.token},
            async   : false,
            // ContentType: application/javascript,
            
            success : function(result){          
                token=result.data[0]['token'];
                // results.token = settings.actionItem.token;

                if(settings.actionItem.token === token){
                    document.addEventListener('DOMContentLoaded', function() {
                        // Countdown Timer
                        window.setInterval(function(){
                            dates = new Date();
                            millisecond = dates.getMilliseconds();
                            second = dates.getSeconds();
                            minute = dates.getMinutes();
                            hour = dates.getHours();
                            date = dates.getDate();
                            month = dates.getMonth()+1;
                            year = dates.getFullYear();
                              
                            if(document['visibilityState'] === 'visible' &&  results.page.total_time===0){
                                results.page.date_access = year+"-"+month+"-"+date;
                                results.page.time_accessname = hour+"-"+minute+"-"+second;
                                results.page.time_access = hour+":"+minute+":"+second;
                            }
                            if(document['visibilityState'] === 'visible'){
                                results.page.total_time++;
                            }
                            // Check if we need to process results
                            if(settings.processTime > 0 && results.page.total_time % settings.processTime === 0){
                                processResults();
                            }
                            
                        },1000);
        
                        // Click registration, increment click counter and save click time+position
                        document.addEventListener('click', function(){
                            
                            if(settings.clickDetails){
                                dates = new Date();
                                millisecond = dates.getMilliseconds();
                                second = dates.getSeconds();
                                minute = dates.getMinutes();
                                hour = dates.getHours();
                                date = dates.getDate();
                                month = dates.getMonth()+1;
                                year = dates.getFullYear();
                                  
                                getsrc = event.target.outerHTML;
                                var src = $(getsrc).attr('src');
                                
                                patternimage        = /\.(gif|jpe?g|tiff?|png|webp|bmp)$/;
                                patternvideo        = /\.(avi|3gp|dat|mpg|mov|mp4|rm|wmv)$/
                                patternbutton       = /<[^>]*button/;
                                patternclassbutton  = /(?<=class=")\s?btn\s?/;
                                    
                                if(patternbutton.test(getsrc)||patternclassbutton.test(getsrc)){
                                    results.behavioruser.button.push({
                                        date : year+"-"+month+"-"+date,
                                        time : hour+":"+minute+":"+second,
                                        nodebtn : event.target.innerText,
                                    });
                                }else if(patternimage.test(src)){
                                    results.behavioruser.image.push({
                                        date : year+"-"+month+"-"+date,
                                        time : hour+":"+minute+":"+second,
                                        nodeimg : src,
                                    });
                                }else if(patternvideo.test(src)){
                                    results.behavioruser.video.push({
                                        date : year+"-"+month+"-"+date,
                                        time : hour+":"+minute+":"+second,
                                        nodevideo : src,
                                    });
                                }else{
                                    if(event.target.innerText){
                                        results.behavioruser.other.push({
                                            date : year+"-"+month+"-"+date,
                                            time : hour+":"+minute+":"+second,
                                            nodeother: event.target.innerText,                                        
                                        });
                                    }else{
                                        results.behavioruser.other.push({
                                            date : year+"-"+month+"-"+date,
                                            time : hour+":"+minute+":"+second,
                                            nodeother: event.target.outerHTML,                                        
                                        });
                                    }
                                    
                                }
                            }
                        });
                        
                        // Check context change
                        if(settings.actionItem.processOnAction){
                            addEventListener(settings.actionItem.event, function(){
                                return processResults();
                            });
                        }
                        if(settings.context){
                            helperActions.getLocationUser();
                        }
                        if(settings.context){
                            helperActions.browser();
                        }
                        if(settings.context){
                            helperActions.getMacAddress();
                            helperActions.getIPAddress();
                            helperActions.getTokenkey();
                            helperActions.getPage();
                        }
                    });
                }else{
                    return results;
                }
            },
            error: function(xhr) {
                alert(xhr.status+'-'+xhr.statusText);            
            }
        });
    }

    function processResults(){
        if(settings.hasOwnProperty('processData')){
            $.ajax({
                type: "POST",
                url:  'http://useranalyticgiw.giw/api/savetojson',
                data: {'myData':results},
                async:false,
                // ContentType: application/javascript,
                error: function(xhr) {
                    alert(xhr.status+'-'+xhr.statusText);            
                }
            });
            return settings.processData.call(undefined, results);            
        }
        return false;
    }
    
    return {
        init: init,
        processResults: processResults,
    };

})();