
angular.module('productsMainModule')

.controller('addToModalController', [
    '$scope', '$rootScope', '$uibModalInstance', 'args', '$http', '$q', 'uniqFilter', 'addToService', 
    function ($scope, $rootScope, $uibModalInstance, args, $http, $q, uniqFilter, addToService) {
    
    $scope.mode = 'addTo';

    $scope.data = {
        newDocumentType: undefined,
        document: 'none',
        newTitle: undefined,
        products: args.products
    };

    $scope.state = {
        type: args.type,
        modalTitle: getTitle(args.type),
        items: undefined,
        isBusy: true,
        isNewVisible: false
    };

    $scope.isNewTitleVisible = function (document) {
        return document && document.startsWith('new');
    };

    $scope.okButtonText = function (id) {
        const found = $scope.lookupDocument(id);
        if (found) {
            return 'Add';
        }
        if (id && id.startsWith('new')) {
            return getButtonTextNew(args.type);
        }
        return 'Add';
    };

    $scope.lookupDocument = function (id) {
        return $scope.state.items && $scope.state.items.filter(function (item) { return item.id == id; })[0];
    };

    $scope.new = function (type) {
        $scope.state.isNewVisible = true;
        $scope.data.document = 'none';

        switch (type) {
            case 'invoice': $scope.data.newDocumentType = 'new_tax_invoice'; break;
            case 'quote': $scope.data.newDocumentType = 'new_quote'; break;
            case 'order': $scope.data.newDocumentType = 'new_credit_note'; break;
            case 'template': $scope.data.newDocumentType = 'new_template'; break;
            case 'project': $scope.data.newDocumentType = 'new'; break;
        }
    }

    $scope.existing = function (document) {
        $scope.state.isNewVisible = false;
        $scope.data.newDocumentType = undefined;
        $scope.data.newTitle = undefined;
    }

    $scope.ok = function () {
        $scope.state.isBusy = true;
        addTo(args.type, $scope.data).then(function (response) {
            $scope.mode = 'success';
            $scope.lastDocumentId = response.data[0];
            $scope.state.isBusy = false;
            $rootScope.$broadcast('product.search.reload');
        }, function (err) {
            $uibModalInstance.close(err);
            $scope.state.isBusy = false;
            
            if (err && err.message) {
                $.jGrowl(err.message, {theme : 'error'});
            }
            console.error(err);
        });
    };
    
    $scope.cancel = function () {
        if ($scope.mode === 'success') {
            $uibModalInstance.close(true);
        } else {
            $uibModalInstance.close(false);
        }
    };

    $scope.view = function (type, id) {
        switch (type) {
            case 'invoice': window.location.href = '/QuotetoolQuotes/invoices/edit/' + (id || ''); break;
            case 'quote': window.location.href = '/QuotetoolQuotes/quotes/edit/' + (id || ''); break;
            case 'order': window.location.href = '/MyOrders/Quotes'; break;
            case 'template': window.location.href = '/Templates/edit/' + (id || ''); break;
            case 'project': window.location.href = '/invoices/view/' + (id || ''); break;
        }
    }

    $('#add_to_server_error').html('');
    getItems().then(function (items) {
        $scope.state.items = items;
    }, function (error) {
        if (error && error.type === 'project_try_again') {
            $scope.mode = 'error';
            setTimeout(function () {
                $('#add_to_server_error').html(error.message);
            }, 10);
        }
    });

    function getItems() {
        var q = $q.defer();

        $scope.state.isBusy = true;

        $http.get(getItemsUrl(args.type) + '?_=' + Date.now(), {
            'headers': { 'X-Requested-With' :'XMLHttpRequest'} // Server returns different results for non-AJAX and AJAX requests
        }).then(function(res) {
            
            if (args.type === 'project' && res.data.indexOf('try again') > -1) {
                // Handle error when adding invoice to a project
                return q.reject({ type: 'project_try_again', message: res.data });
            }

            var results = [];
            $($.parseHTML('<div>'+res.data+'</div>')).find('form[action*=add] option').each(function (i, x) { 
                if($(x).attr('value').match(/^\d+$/)) { 
                    results.push({
                        id: $(x).attr('value'),
                        text: $(x).text()
                    });
                }
            });
            results = uniqFilter(results, 'id');
            $scope.state.isBusy = false;
            q.resolve(results);
        }, function(err) {
            $scope.state.isBusy = false;
            q.reject(err);
        });

        return q.promise;
    }

    function addTo(type, data) {
        switch (type) {
            case 'invoice': return addToService.addToInvoice(data);
            case 'quote': return addToService.addToQuote(data);
            case 'order': return addToService.addToOrder(data);
            case 'template': return addToService.addToTemplate(data);
            case 'project': return addToService.addToProject(args.invoice_id, data);
        }
    }

    $scope.getType = function (type) {
        switch (type) {
            case 'invoice': return 'Invoice';
            case 'quote': return 'Quote';
            case 'order': return 'Order';
            case 'template': return 'List';
            case 'project': return 'Project';
        }
    };

    function getTitle(type) {
        switch (type) {
            case 'invoice': return 'Add Products to Invoice';
            case 'quote': return 'Add Products to Quote';
            case 'order': return 'Add Product to Order';
            case 'template': return 'Add Products to List';
            case 'project': return 'Add Invoice to Job';
        }
    }

    function getButtonTextNew(type) {
        switch (type) {
            case 'invoice': return 'Add to New Invoice';
            case 'quote': return 'Add to New Quote';
            case 'order': return 'Add to New Order';
            case 'project': return 'Add to New Project';
        }
    }

    function getItemsUrl(type) {
        switch (type) {
            case 'invoice': return '/quotes/quotes/add_product/TaxInvoice';
            case 'quote': return '/quotes/quotes/add_product/Quote';
            case 'order': return '/baskets/add_product';
            case 'template': return '/templates/add_product';
            case 'project': return '/projects/addInvoice/' + args.invoice_id;
        }
    }

}]);