var TrackPuzzle = {
    init: function(puzzleId, serviceURL, isTrackingActive, statisticsOptions) {
        //First, determine is tracking will be active
        if (isTrackingActive && navigator.onLine)
        {
            // 20% chance that tracking is active
            //if (Math.random() < 0.2)
                this.isTrackingActive = true;
            
            window.onbeforeunload = function() {
                if (typeof TrackPuzzle.savePuzzleStatistics == "function")
                    TrackPuzzle.savePuzzleStatistics();

                if (typeof TrackPuzzle.sendPuzzleStatistics == "function")
                    TrackPuzzle.sendPuzzleStatistics();
            };
        }

        //Set class variables
        this.puzzleId = puzzleId;
        this.serviceURL = serviceURL;
        this.hasSentData = false;
        //Start tracking by setting game start time
        this.saveGameStartTime();

        this.initSpecific(puzzleId, serviceURL, isTrackingActive);

        if (typeof statisticsOptions !== 'undefined')
            this.statisticsOptions = JSON.parse(statisticsOptions);
//        this.savePuzzleCompletion();
    },
    initSpecific: function(puzzleId, serviceURL, isTrackingActive) {
    },
    gameRestart: function() {
        this.hasSentData = false;

        this.analyticsEvent("button, click, clear");
    },
    getCurrentTime: function() {
        return new Date().getTime();
    },
    saveGameStartTime: function() {
        if (!this.isTrackingActive)
            return;
        
        if (!this.gameDuration)
        {
            this.gameDuration = {
                start: undefined,
                duration: undefined
            };
        }
        
        this.gameDuration.start = this.getCurrentTime();
    },
    saveGameEndTime: function() {
        if (!this.isTrackingActive)
            return;
        
        if (!this.gameDuration)
        {
            this.gameDuration = {
                start: this.getCurrentTime(),
                duration: undefined
            };
        }

        this.gameDuration.duration = this.getCurrentTime() - this.gameDuration.start;

        this.saveStat('game_duration', this.gameDuration.duration);
    },
    savePuzzleCompletion: function() {
        if (!this.isTrackingActive)
            return;
        
        var cells = $(Puzzle.defaults.gridId).find(Puzzle.defaults.cellsId).not(Puzzle.defaults.blankClass);
        var inputtedCount = 0;
        
        for (var i = 0; i < cells.length; i++)
        {
            var cellInput = $(cells[i]).find(Puzzle.defaults.cellInputId).html();

            if (cellInput && cellInput.length > 0)
                inputtedCount++;
        }
        
        this.puzzleCompletion = (inputtedCount / cells.length).toFixed(2);

        this.saveStat('game_completion', this.puzzleCompletion);
    },

    endGame: function() {
    },

   saveStat: function(key, name, value, replace_value)
   {
        if (!this.isTrackingActive || !this.statisticsOptions[key])
            return;

        var replace = (typeof replace_value !== 'undefined') ? replace_value : false;

        if (key)
        {
            var obj = { 'key' : key};

            if(typeof name !== 'undefined')
            {
                if(typeof name === 'string')
                {
                    obj.text = name;
                }
                else if(typeof name == 'number')
                {
                    obj.int = name;
                }
            }

            if(value && (typeof value == 'number'))
            {
                obj.int = value;
            }

            if (replace)
            {
                var found = false;

                for (var i = 0; i < this.statsData.length; i++)
                {
                    if (this.statsData[i].text == name)
                    {
                        if (this.statsData[i].int)
                            this.statsData[i].int = value;

                        found = true;
                        break;
                    }
                }

                if (!found)
                    this.statsData.push(obj);
            }
            else
            {
                this.statsData.push(obj);
            }
            
        }

    },

    beforeSendStats: function() {

        if (!this.isTrackingActive || this.hasSentData)
            return;
        
        this.saveGameEndTime();
        this.savePuzzleCompletion();
        this.saveStat('flags', this.flags);

        var score = puzzleScore.getScore();

        //console.log('Statistics flags: ' + this.flags);

        if (score > 0)
            this.saveStat('score', score);
    },

    sendPuzzleStatistics: function(isClear) {
        if (!this.isTrackingActive || this.statsData.length == 0)
            return;
        
        //End game timing and puzzle completion tracking
        this.endGame();

        this.beforeSendStats();

        //console.log(this.statsData);

        $.ajax({
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            dataType : "json",
            type : "POST", 
            async : false,
            timeout: 5000,
            url : TrackPuzzle.serviceURL,
            data : {
                puzzle_id : TrackPuzzle.puzzleId,
                user_id: UserManagement.getUserId(),
                data: JSON.stringify(TrackPuzzle.statsData)
            },
            success: function(msg)
            {
                TrackPuzzle.statsData = [];
                TrackPuzzle.didSendPuzzleStatistics();
                TrackPuzzle.hasSentData = true;

                if(isClear)
                {
                    TrackPuzzle.gameRestart();
                }
            },
            complete: function(msg)
            {
                TrackPuzzle.statsData = [];
            }
        });
    },

    didSendPuzzleStatistics: function() {

    },

    analyticsEvent: function(category, action, label, value)
    {

        if (typeof ga != 'undefined')
        {
            if(value)
            {
                ga('send', 'event', category, action, label, value);  // value is a number.
            }
            else if(label)
            {
                ga('send', 'event', category, action, label);
            }
            else if(action)
            {
                ga('send', 'event', category, action);
            }
            else if(category)
            {
                ga('send', 'event', category);
            }
        }
        else
        {
            //console.log("Failed to log event, GA is undefined");
        }

        return false;
    },

    statsData: [],
    isTrackingActive: false,
    statisticsOptions: undefined,
    puzzleId: undefined,
    gameDuration: {},
    puzzleCompletion: 0,
    serviceURL: undefined,
    puzzleStart: 0,
    hasSentData: false,
    flags: 0,
};