/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */

'use strict';

var Logger = require('dw/system/Logger');
var logger = Logger.getLogger('Redsys', 'Redsys');

/**
 * Generates the RMA number for the return based on certain rules
 */
function getRMANumber(order) {
    var CustomObjectMgr = require('dw/object/CustomObjectMgr');
    var StringUtils = require('dw/util/StringUtils');

    var returns = CustomObjectMgr.queryCustomObjects("RedsysReturn", "custom.orderNo = {0}", "creationDate desc", order.orderNo);
	var number;
	if(returns.count==0) {
		number = 1;
	} else {
		number = parseInt(returns.first().custom.ID.substr(-2,2)) + 1;
	}
    var numberFormat = StringUtils.formatNumber(number, '00');
    var rmaNumber = order.orderNo + numberFormat;

    return rmaNumber;
}

/**
 * Given an order and a return data, it generates all objects needed.
 *
 * @param {object} oOrder Order from where generate the returns.
 * @param {object} oReturnData Return object containing all needed data.
 * @return boolean True if no errors raised.
 */
function doGenerateReturn(oOrder, oReturnData)
{
	var customObjectMgr = require('dw/object/CustomObjectMgr'),
		Transaction = require ('dw/system/Transaction'),
		bTransactionOK = false;

	if ('string' === typeof oOrder) {
		var s = request.httpParameterMap;
		oOrder = require ('dw/order/OrderMgr').getOrder(oOrder);
	}

	var returnID = getRMANumber(oOrder);

	var productArr = [];
	var productMgr = require('dw/catalog/ProductMgr');
	var StoreMgr = require('dw/catalog/StoreMgr');

	// General return object
	Transaction.wrap(function(){
		var COReturn = customObjectMgr.createCustomObject("RedsysReturn", dw.util.UUIDUtils.createUUID());

		COReturn.custom.ID = returnID;
		COReturn.custom.orderNo = oOrder.orderNo;
		COReturn.custom.type_return = oReturnData.type;
		COReturn.custom.refundedAmount = new Number(oReturnData.refundedAmount);
		COReturn.custom.returnShippmentCosts = oReturnData.returnShippmentCost;
		COReturn.custom.redsysResponse = oReturnData.redsysResponse;
        if(oReturnData.products!=null)
		    COReturn.custom.products = JSON.stringify(oReturnData.products);
		COReturn.custom.log = oReturnData.log;
		bTransactionOK = true;
	});

	if (bTransactionOK) {

		Transaction.wrap (function () {
			oOrder.addNote ('Order - Redsys Return', oReturnData.log);
		});

	}

	return (bTransactionOK)
		? returnID
		: null
	;
}

function getReturnFromId(idReturn) {
	var CustomObject = dw.object.CustomObjectMgr.getCustomObject(
        "RedsysReturn",
        idReturn
    );

    if (CustomObject) {
        return CustomObject;
    } else {
        return null;
    }
}

function getReturnLines(CustomReturn) {
	if(CustomReturn.custom.type_return=="PRODUCTS") {
		return JSON.parse(CustomReturn.custom.products);
	} else {
		return null;
	}
}

function getOrder(CustomReturn) {
	var Order = dw.order.OrderMgr.getOrder(CustomReturn.custom.orderNo);
	return Order;
}

function isAvailableRefund(nOrder) {
	var order = dw.order.OrderMgr.getOrder(nOrder);
	var available = {allow: true, hasReturns: false, returns: [], refundedAmount: 0, forRefund: 0, forRefundItems: [], refundedItems: {}, shippingRefunded:false};
	if(!order) {
		return available;
	}

	var CustomObjectMgr = require('dw/object/CustomObjectMgr');

	// Get custom obejects
	var returns = CustomObjectMgr.queryCustomObjects ("RedsysReturn", 'custom.orderNo={0}', 'creationDate desc', nOrder);
	if (returns.count) {
		available.hasReturns = true;
		while (returns.hasNext()) {
			var oneReturn = returns.next();
			if(oneReturn.custom.type_return=="PRODUCTS") {
				var products = JSON.parse(oneReturn.custom.products);
				if(products.length>0) {
					for(var p=0; p<products.length; p++) {
						var product = products[p];
						var qty = product.qty;
						var sku = product.sku;
						if(available.refundedItems.hasOwnProperty(sku)) {
							available.refundedItems[sku] = parseInt(available.refundedItems[sku]) + parseInt(qty);
						} else {
							available.refundedItems[sku] = parseInt(qty);
						}
					}
				}
			}
			if(oneReturn.custom.returnShippmentCosts==true) {
				available.shippingRefunded = true;
			}
			available.returns.push(oneReturn);
			available.refundedAmount = parseFloat(available.refundedAmount) + parseFloat(oneReturn.custom.refundedAmount);
		}
	}
	available.forRefund = parseInt(order.totalGrossPrice.value) - available.refundedAmount;

	var lineProducts = order.getAllProductLineItems();

	for (var i = 0; i < lineProducts.length; i++) {

		var qtyRefunded = available.refundedItems.hasOwnProperty(lineProducts[i].product.ID) ? parseInt(available.refundedItems[lineProducts[i].product.ID]) : 0;
		var oProduct = {
			sku: lineProducts[i].product.ID,
			ca: {},
			name: lineProducts[i].product.name,
			qty: lineProducts[i].quantityValue - qtyRefunded,
			qtyOriginal: lineProducts[i].quantityValue,
			price: lineProducts[i].adjustedGrossPrice.divide (lineProducts[i].quantity.value),
			obj: lineProducts[i],
			returns: [],
			returnable: (lineProducts[i].quantityValue - qtyRefunded) > 0 ? true : false
		};
		available.forRefundItems.push(oProduct);
	}

	if(available.refundedAmount >= (order.adjustedMerchandizeTotalGrossPrice.value + order.adjustedShippingTotalGrossPrice.value))
		available.allow = false;

	return available;
}

module.exports = {
    getRMANumber: getRMANumber,
    doGenerateReturn: doGenerateReturn,
	getReturnFromId: getReturnFromId,
	getOrder: getOrder,
	getReturnLines: getReturnLines,
	isAvailableRefund: isAvailableRefund
};
