var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;
var ItemDetailsConstants = require('../constants/itemDetailsConstants');
var ItemWithDetails = require('../models/itemWithDetails');
var _ = require('underscore');


var _itemWithDetails = new ItemWithDetails();
var _images = [];
var _currentImage = 0;
var _animating = false;
var _count;


var getItemIdFromUrl = 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 = /artikal\/(\d+)\//g;
    var match = itemIdRegex.exec(url);

    return match[1];
};

var fetchItemWithDetails = function() {
    var id = getItemIdFromUrl();
    if (id !== undefined && _itemWithDetails.id !== id) {
        var item = new ItemWithDetails({
            id: id
        });
        _itemWithDetails = item;
        item.fetch({
            success: function() {
                _images = (_itemWithDetails.get("multi_media_descriptions") || []).map(function(mmd) {
                    return mmd.resized_url;
                });
                _count = _images.length;
                _currentImage = 0;
                _animating = false;
                ItemWithDetailsStore.emitChange();
            }
        });
    }
};

var handlNextImage = function() {
    if (_animating) return;
    var next = _currentImage + 1;
    if (next >= _count) next = 0;
    handleSelectImage(next);
};

var handlePrevImage = function() {
    if (_animating) return;
    var next = _currentImage - 1;
    if (next < 0) next = _count - 1;
    handleSelectImage(next);
};


var handleSelectImage = function(index) {
    if (_animating) return;
    _animating = true;
    _currentImage = index;
    setTimeout(function() {
        _animating = false;
    }, 300);
};



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

    getState: function() {

    
        var firstImage = _images[0] || "https://res.cloudinary.com/lfvt7ps2n/image/upload/c_fit,h_172,w_226/v1421732950/http_www.asms.ru_bitrix_templates_main_images_nophoto_irnofq.png";
        return {
            item: _itemWithDetails,
            images: _images,
            currentImage: _currentImage,
            count: _count,
            firstImage: firstImage
        }

    },


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

    // 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 ItemDetailsConstants.LOAD_ITEM_WITH_DETAILS:
            fetchItemWithDetails();
            break;

        case ItemDetailsConstants.NEXT_CAROUSEL_IMAGE:
            handlNextImage();
            break;

        case ItemDetailsConstants.PREVIOUS_CAROUSEL_IMAGE:
            handlePrevImage();
            break;

        case ItemDetailsConstants.SELECT_CAROUSEL_IMAGE:
            handleSelectImage(action.index);
            break;

        default:
            return true;
    }

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

});

module.exports = ItemWithDetailsStore;