jQuery( function ( $ ) {

    var orderIdsInput = $('input[name="massOrderIds"]');
	if(orderIdsInput.length > 0){
        var orderIdsRaw = orderIdsInput.val();
        var orderIds = [];
        if (orderIdsRaw.indexOf(",") == -1) {
            orderIds = [orderIdsRaw];
        } else {
            orderIds = orderIdsRaw.split(",");
        }
        var promises = [];
		var processedIds = [];
		var successIds = [];
		var problemIds = [];
		var alreadyIds = [];

		processId(orderIds);
	}

	function processId(orderIds){

        $.each(orderIds, function(index, el) {
            var orderId = el;

            // get all suborders
            var subordersRaw = $('input[name="bulk_order_'+orderId+'"]').val();
            var suborders = [];
            if (subordersRaw.indexOf(",") == -1) {
                suborders = [subordersRaw];
            } else {
                suborders = subordersRaw.split(",");
            }

            $.each(suborders, function(index, suborder) {
                processedIds.push({id: orderId, suborderKey: suborder});
            });

            promises[orderId] = new Promise(function(resolve, reject) {
                $.ajax({
                    url: ajaxurl,
                    data: { action: 'mass_order', security: ajax_nonce, order_id: orderId },
                    dataType: "json",
                    error: function() {
                        problemIds.push({id: orderId, suborderKey: suborder});
                        showProcess(processedIds, successIds, problemIds, alreadyIds);
                        resolve("error !");
                    },
                    success: function(data){
                        $.each(suborders, function(index, suborder) {
                            if(typeof data[suborder].error != 'undefined'){
                                problemIds.push({id: orderId, suborderKey: suborder});
                            } else if (typeof data[suborder].already != 'undefined') {
                                alreadyIds.push({id: orderId, suborderKey: suborder});
                                showProcess(processedIds, successIds, problemIds, alreadyIds);
                            } else {
                                successIds.push({id: orderId, suborderKey: suborder});
                                showProcess(processedIds, successIds, problemIds, alreadyIds);
                            }

                            if (index == suborders.length-1) {
                                showProcess(processedIds, successIds, problemIds, alreadyIds);
                                resolve();
                            }
                        });
                    }
                });
            });
        });

        // wait a bit otherwise this runs before any promise is added
        setTimeout(function() {
            Promise.all(promises).then(function() {
                $('#mass-order .ongoing').hide();
                $('#mass-order .finished').show();
                if (problemIds.length > 0 || alreadyIds.length > 0) {
                    $('#mass-order .finished').addClass('failure');
                    if (problemIds.length > 0) {
                        $('#mass-order .finished .warning').show();
                    }
                    if (alreadyIds.length > 0) {
                        $('#mass-order .finished .already').show();
                    }
                } else {
                    $('#mass-order .finished').addClass('success');
                }
            });
        }, 2000);
	}

	function queryParameters(){
		var result = {};

		var params = window.location.search.split(/\?|\&/);

		params.forEach( function(it) {
			if (it) {
				var param = it.split("=");
				result[param[0]] = param[1];
			}
		});

		return result;
	}

	function showProcess(processedIds, successIds, problemIds, alreadyIds) {
        var processedIdsHtml = [];
        for (i=0;i<processedIds.length;i++) {
            processedIdsHtml.push(translations.shipment+" "+processedIds[i].suborderKey+" ("+translations.order+" "+processedIds[i].id+")");
        }
		$('#mass-order .processed_id').html(processedIdsHtml.join(', '));

        var successIdsHtml = [];
        for (i=0;i<successIds.length;i++) {
            successIdsHtml.push(translations.shipment+" "+successIds[i].suborderKey+" ("+translations.order+" "+successIds[i].id+")");
        }
		$('#mass-order .success_ids').html(successIdsHtml.join(', '));

        var problemIdsHtml = [];
        for (i=0;i<problemIds.length;i++) {
            problemIdsHtml.push(translations.shipment+" "+problemIds[i].suborderKey+" ("+translations.order+" "+problemIds[i].id+")");
        }
		$('#mass-order .problem_ids').html(problemIdsHtml.join(', '));

        var alreadyIdsHtml = [];
        for (i=0;i<alreadyIds.length;i++) {
            alreadyIdsHtml.push(translations.shipment+" "+alreadyIds[i].suborderKey+" ("+translations.order+" "+alreadyIds[i].id+")");
        }
		$('#mass-order .already_ids').html(alreadyIdsHtml.join(', '));
	}
});
