var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;
var ItemConstants = require('../constants/itemConstants');
var ItemCollection = require('../models/itemCollection');
var ItemWithDetails = require('../models/itemWithDetails');
var _ = require('underscore');

// Define initial data points
var _items = new ItemCollection(),
    _itemWithDetails = new ItemWithDetails(),
    _bestSellingForSection = new ItemCollection(),
    _itemsByCategory = new ItemCollection(),
    _bestSellingForGroup = new ItemCollection();


var loadItemsForFrontpage = function() {
    items = _items
    items.setClassificationType(0);
    items.setLimit(30);
    items.setOffset(0);

    items.fetch({
        success: function() {
            ItemStore.emitChange();
        }
    });
};

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

    if (match) {
        return match[1];
    }
};

var fetchItemWithDetails = function() {
    var id = getItemIdFromUrl();
    if (id !== undefined && _itemWithDetails.id !== id) {
        var item = new ItemWithDetails({
            id: id
        });
        item.fetch({
            success: function() {
                _itemWithDetails = item;
                ItemStore.emitChange();
            }
        });
    }
}

var fetchItemsByCategory = function(categoryId, offset, limit, query) {
    //var items = _itemsByCategory;
    var items = new ItemCollection();
    items.clearFilter();
    items.setClassificationType(2);
    items.setClassificationId(categoryId);
    items.setLimit(limit);
    items.setOffset(offset);

    for (var key in query) {
        if (query.hasOwnProperty(key) && key != 'limit' && key != 'offset') {
            items.addFilter(key, query[key]);
        }
    }

    items.fetch({
        success: function(collection, response, options) {
            var total = options.xhr.getResponseHeader('x-total-count');
            items.setTotalCount(total);

            ItemStore.emitChange();
        }
    });

    _itemsByCategory = items;
};

var fetchBestSellingItemsForSection = function(sectionId) {

    var items = _bestSellingForSection;
    items.setClassificationType(1);
    items.setClassificationId(sectionId);
    items.setLimit(30);
    items.setOffset(0);

    items.fetch({
        success: function() {
            ItemStore.emitChange();
        }
    });
};


var fetchBestSellingItemsForGroup = function(groupId) {

    var items = _bestSellingForGroup;
    items.setClassificationType(4);
    items.setClassificationId(groupId);
    items.setLimit(30);
    items.setOffset(0);

    items.fetch({
        success: function() {
            ItemStore.emitChange();
        }
    });
};


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

    getItemsForCategory: function() {
        return _itemsByCategory;
    },
    getBestSellingForSection: function() {

        return _bestSellingForSection;
    },
    // item with details
    getLoadedItemWithDetails: function() {
        return _itemWithDetails;
    },

    getItemsForGroup: function() {
        return _bestSellingForGroup;
    },


    // Return All Items
    getItems: function() {
        return _items;
    },

    // 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);
    }

});


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

    switch (action.actionType) {

        case ItemConstants.LOAD_ITEM_WITH_DETAILS:
            fetchItemWithDetails();
            break;

        case ItemConstants.LOAD_BSI_FOR_SECTION:
            fetchBestSellingItemsForSection(action.sectionId);
            break;

        case ItemConstants.LOAD_BSI_FOR_ITEM_GROUP:
            fetchBestSellingItemsForGroup(action.groupId);
            break;

        case ItemConstants.LOAD_FOR_FRONTPAGE:
            loadItemsForFrontpage();
            break;
        case ItemConstants.LOAD_BY_CATEGORY:
            fetchItemsByCategory(action.categoryId, action.offset, action.limit, action.query);
            break;

        default:
            return true;
    }

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

});

module.exports = ItemStore;
