(function (paw, fn) {
    function IdentSearchComponent(settings, popup){
        var self = this;
        this.isInit = false;
        this.settings = paw.lang.append({
            detailsApiUrl: '/SetItem/GetDetails',
            onSelectReturn: null,
            onAddPosition: null,
            onAddAll: null
        }, settings || {});
        this.popup = popup;

        this.data = {
            stock: [],
            review: []
        };
        this.selection = {
            stock: [],
            review: []
        };

        this.searchFields = new paw.com.identSearch.IdentSearchFields(function () {
            self.datatable.stock.resetScrollTop();
            self.datatable.review.resetScrollTop().reload();
        });

        this.datatable = {
            stock: null,
            review: null
        };

        this.actions = {
            find: {
                selector: '.ident-search-actions .ident-search-find',
                onSelected: function(){
                    self.datatable.review.reload();
                }
            },
            selectReturn: {
                selector: '.ident-search-actions .ident-search-select-return',
                onSelected: function(){
                    if(self.datatable.review.selection.length === 0){
                        return;
                    }

                    self.selectIdent().then(function () {
                        self.popup.hide();
                        if (paw.utils.value.isFunction(self.settings.onSelectReturn)) {
                            self.settings.onSelectReturn(identDetails, self.datatable.review.selection, self.datatable.stock.selection, self.searchFields.searchFieldsData.Quantity);
                        }
                    });
                }
            },
            addPosition: {
                selector: '.ident-search-actions .ident-search-select-add-position',
                onSelected: function () {
                    self.selectIdent().then(function () {
                        if (paw.utils.value.isFunction(self.settings.onAddPosition)) {
                            self.settings.onAddPosition(self.datatable.review.selection, self.datatable.stock.selection, self.searchFields.searchFieldsData.Quantity);
                        }
                    }).then(function () {
                        fn.triggerPositionAdd();
                    });
                }
            },
            addAll: {
                selector: '.ident-search-actions .ident-search-select-add-all',
                onSelected: function () {
                    if(paw.utils.value.isFunction(self.settings.onAddAll)){
                        self.settings.onAddAll(self.searchFields.searchFieldsData.Quantity);
                    }
                }
            }
        };

        this.viewMarkup = null;
    }

    IdentSearchComponent.prototype.init = function(){
        var self = this;
        this.searchFields.init().then(function(){
            self.initTables();
            self.initActions();
        }).finally(function(){
            self.isInit = true;
            var $preloader = $('.ident-search-content').find('.ident-search-preloader-holder');
            $preloader.css({
                display: 'none'
            });
        });
    };

    IdentSearchComponent.prototype.initTables = function(){
        var self = this;
        this.datatable.stock = new paw.com.identSearch.IdentSearchStockTable(this.searchFields.searchData);
        self.datatable.review = new paw.com.identSearch.IdentSearchReviewTable(self.searchFields.searchData, self.datatable.stock)
        self.datatable.review.init().then(function(){
            return self.datatable.stock.init();
        }).catch(function(){

        });
    };

    IdentSearchComponent.prototype.initActions = function(){
        for(var k in this.actions){
            var action = this.actions[k];
            $(action.selector).on('click', action.onSelected);
        }
    };

    IdentSearchComponent.prototype.destroy = function(){
        this.searchFields.destroy();

        for(var k in this.actions){
            var action = this.actions[k];
            $(action.selector).off('click', action.onSelected);
        }

        this.datatable.stock.destroy();
        this.datatable.review.destroy();
    };

    IdentSearchComponent.prototype.$view = function(){
        if(paw.utils.value.isSet(this.viewMarkup)){
            return this.viewMarkup;
        }
        var $view = $('[data-ident-search-content]');
        this.viewMarkup = $view.html();
        $view.remove();
        return this.viewMarkup;
    };

    IdentSearchComponent.prototype.initSelectionFieldDef = function(){
        return {
            options: [],
            mappedValue: function(opt){
                return opt.Key;
            },
            mappedLabel: function(opt){
                return opt.Value;
            }
        };
    };

    IdentSearchComponent.prototype.fetchIdentDetails = function (ident) {
        var d = paw.utils.async.defer();
        $.ajax({
            method: 'GET',
            url: this.settings.detailsApiUrl + '?' + $.param({
                id: ident
            }),
            success: function (identDetails) {
                d.resolve(identDetails);
            },
            error: function () {
                console.error("Error while loading ident details");
                d.reject();
            }
        });
        return d.promise;
    };

    IdentSearchComponent.prototype.addIdentToDocument = function (identDetails) {
        return fn.setInvoiceItemData(identDetails, this.settings.priceType, this.settings.discountType, this.searchFields.searchData.Quantity);
    };

    IdentSearchComponent.prototype.selectIdent = function () {
        var self = this;
        return this.fetchIdentDetails(this.datatable.review.selection[0].Ident).then(function (identDetails) {
            return self.addIdentToDocument(identDetails);
        });
    };

    paw.com.identSearch.IdentSearchComponent = IdentSearchComponent;
})(paw, {
    setInvoiceItemData: setInvoiceItemData,
    triggerPositionAdd: triggerPositionAdd
});