var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;
var Globals = require('../globals');

var NavigationConstants = require('../constants/navigationConstants')
var _ = require('underscore');




var getGroupIdFromUrl = function() {
    // ugly but it seems to me that
    // router does not want to expose its
    // state (for phylosophical reasons)
    var url = document.URL;
    var itemIdRegex = /grupa\/(\d+)\//g;
    var match = itemIdRegex.exec(url);

    var result = Globals.ItemGroupIdOfStartPage;
    if (match) {
        result = match[1]
    }
    return result;
};

// Extend ItemStore with EventEmitter to add eventing capabilities
var NavigationStore = _.extend({}, EventEmitter.prototype, {

    getGroupIdFromUrl: getGroupIdFromUrl,

    // Emit Change event
    emitChange: function() {
        this.emit('change');
    },

    // Add change listener
    addChangeListener: function(callback) {
        this.on('change', callback);
    },

    // Remove change listener
    removeChangeListener: function(callback) {
        this.removeListener('change', callback);
    },

    hideCart: function() {
        // TODO: figure out how to find this out using Router
         var url = document.URL;
        var itemIdRegex = /\/(korpa|dostava)/g;
        var match = itemIdRegex.exec(url);
        if (match) {
            return true;
        } else {
            return false;
        }
    }

});




// Register callback with AppDispatcher
NavigationStore.dispatchToken = AppDispatcher.register(function(payload) {
    var action = payload.action;

    switch (action.actionType) {

        case NavigationConstants.CHANGE_URL:
            ga('send', 'pageview', action.url);
            var router = require('../router');
            setTimeout(function() {
                router.transitionTo(action.url);
            }, 0);
            break;

        default:
            return true;
    }

    // If action was responded to, emit change event
    NavigationStore.emitChange();
    return true;

});

module.exports = NavigationStore;